简体   繁体   English

在C#中从字符串转换为DateTime

[英]Conversion from String to DateTime in C#

I want to convert a String to Datetime. 我想将字符串转换为日期时间。 I'm getting an error This is not a valid datetime . 我收到错误消息This is not a valid datetime

The string I want to convert and code are as follows. 我要转换的字符串和代码如下。

string date1 = "9/13/2012 5:26:06 PM";
TimePart = DateTime.ParseExact(date1, "M/d/yyyy HH:mm:ss tt", System.Globalization.CultureInfo.InvariantCulture);

我认为您的format参数应该是M/dd/yyyy h:mm:ss tt

It looks like your format is really M/d/yyyy h:mm:ss tt . 看来您的格式确实是M/d/yyyy h:mm:ss tt The difference is h (12-hour, with only as many digits as needed) instead of HH (24-hour, with leading 0 to pad to 2 digits). 区别是h (12小时,只需要多少位数)而不是HH (24小时,前导0填充到2位数字)。

If the input format can vary at all, you should use DateTime.Parse instead so that you don't have to tell it the exact format. 如果输入格式可能完全不同,则应改用DateTime.Parse这样就不必告诉它确切的格式了。 ParseExact is faster, and requires that it matches the specified format, which may be preferable in your cast. ParseExact速度更快,并且要求它匹配指定的格式,这在您的演员表中可能更可取。

You need to use the lowercase h : 您需要使用小写的h

DateTime TimePart = DateTime.ParseExact(
                                date1,
                                "M/d/yyyy h:mm:ss tt",
                                CultureInfo.InvariantCulture);

Console.WriteLine(TimePart); // 09/13/2012 17:26:06

Uppercase "H" is 24-hour time, lowercase "h" is 12-hour time with AM/PM. 大写“ H”为24小时制,小写“ h”为12小时制,具有AM / PM。

You should be using a lower case h for a 12 hour clock (since you have an AM/PM designator). 您应该将小写h用作12小时时钟(因为您有AM/PM指示符)。

Additionally, you should only use one h , as you don't have a leading 0 to the hours, and hh expects it. 另外,您应该只使用一个h ,因为您没有小时数的前导0 ,而hh期望它。

A format string that works: 有效的格式字符串:

"M/d/yyyy h:mm:ss tt"

It looks like the HH isn't matching the "5". 看来HH与“ 5”不匹配。 Try h . 尝试h

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM