从字符串日期时间格式?字符串、日期、格式、时间

2023-09-04 00:44:56 作者:脏话是女汉子的保护色

我如何将字符串转换为DateTime格式?举例来说,如果我有一个字符串,如:

How do I convert a string to DateTime format? For example, if I had a string like:

24/10/2008

我如何获取到DateTime格式?

How do I get that into DateTime format ?

推荐答案

使用DateTime.ParseExact:

string str = "24/10/2008";
DateTime dt = DateTime.ParseExact(str, "dd/MM/yyyy", 
                                  Thread.CurrentThread.CurrentCulture);

(你应该考虑什么样的文化,你真正想要解析它,诚然。)

(You should consider what culture you actually want to parse it in, admittedly.)

编辑:其他的答案已经指定了空作为第三个参数 - 这是等同于使用 Thread.CurrentThread.CurrentCulture

Other answers have specified "null" as the third parameter - this is equivalent to using Thread.CurrentThread.CurrentCulture.

对于其它的格式,请参见自定义日期和时间格式字符串 MSDN中的

For other formats, see "Custom Date and Time Format Strings" in MSDN.