如何在VB.net中将Date转换为格式化字符串?

时间:2022-08-24 20:49:46

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.toString I get a string in the format 16/01/2013 13:00:00.

在将字符串转换为Date时似乎有一百万个问题,但反之亦然。当我使用mydate.toString将Date对象转换为字符串时,我得到一个格式为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对象上看到任何为我这样做的函数,我是否需要使用正则表达式或其他东西?

5 个解决方案

#1


35  

You can use the ToString overload. Have a look at this page for 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

或类似的东西

#2


6  

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

你可以使用format函数来做,这是一个示例:

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

#3


3  

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

#4


2  

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

the capital HH is for 24 hours format as you specified

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

#5


2  

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.

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

#1


35  

You can use the ToString overload. Have a look at this page for 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

或类似的东西

#2


6  

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

你可以使用format函数来做,这是一个示例:

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

#3


3  

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

#4


2  

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

the capital HH is for 24 hours format as you specified

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

#5


2  

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.

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