如何将日期转换为 VB.net 中的格式化字符串?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14359616/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 16:50:05  来源:igfitidea点击:

How to convert a Date to a formatted string in VB.net?

.netvb.netdatedatetimetype-conversion

提问by DisgruntledGoat

There seems to be a million questions here on converting a string to a Date, but not vice-versa. When I convert a Date object to a string using mydate.toStringI get a string in the format 16/01/2013 13:00:00.

关于将字符串转换为日期,这里似乎有一百万个问题,但反之亦然。当我使用将 Date 对象转换为字符串时,mydate.toString我会得到一个格式为 的字符串16/01/2013 13:00:00

But what I really want is 2013-01-16 13:00:00. I can't see any functions on the Date object that do this for me, do I need to use a regex or something instead?

但我真正想要的是2013-01-16 13:00:00. 我在 Date 对象上看不到任何为我执行此操作的函数,我是否需要使用正则表达式或其他东西?

回答by Matt Wilko

You can use the ToString overload. Have a look at this pagefor more info

您可以使用 ToString 重载。查看此页面了解更多信息

So just Use myDate.ToString("yyyy-MM-dd HH:mm:ss")

所以只需使用 myDate.ToString("yyyy-MM-dd HH:mm:ss")

or something equivalent

或等价的东西

回答by Ali Issa

you can do it using the format function, here is a sample:

您可以使用 format 函数来完成,这是一个示例:

Format(mydate, "yyyy-MM-dd HH:mm:ss")

回答by Abdusalam Ben Haj

myDate.ToString("yyyy-MM-dd HH:mm:ss")

the capital HH is for 24 hours format as you specified

大写的 HH 是您指定的 24 小时格式

回答by SubtleStu

I like:

我喜欢:

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
myDate.ToString(timeFormat)

Easy to maintain if you need to use it in several parts of your code, date formats always seem to change sooner or later.

如果您需要在代码的多个部分使用它,则易于维护,日期格式似乎迟早会改变。

回答by Jineesh Uvantavida

Dim timeFormat As String = "yyyy-MM-dd HH:mm:ss"
objBL.date = Convert.ToDateTime(txtDate.Value).ToString(timeFormat)