我想不通,我哪里出错了?
我得到了以下日期时间字符串,需要将其解析为日期时间:
string timestr = "1/20/2014 12:05:16 AM"
我试图像这样解析它:
DateTime.ParseExact( timestr,
"MM/dd/yyyy hh:mm:ss tt",
null);
尝试执行此操作时,它会返回
“字符串未被识别为有效的日期时间”
任何提示?
我想不通,我哪里出错了?
我得到了以下日期时间字符串,需要将其解析为日期时间:
string timestr = "1/20/2014 12:05:16 AM"
我试图像这样解析它:
DateTime.ParseExact( timestr,
"MM/dd/yyyy hh:mm:ss tt",
null);
尝试执行此操作时,它会返回
“字符串未被识别为有效的日期时间”
任何提示?
MM
是01
为了12
改用M
which is for 1
to 12
。
string timestr = "1/20/2014 12:05:16 AM";
var date = DateTime.ParseExact(timestr,
"M/dd/yyyy hh:mm:ss tt",
CultureInfo.InvariantCulture);
Console.WriteLine(date);
输出将是;
1/20/2014 12:05:16 AM
这里一个demonstration
.
有关更多信息,请查看;
还要注意你的小时格式。hh
是01
为了12
,HH
是00
为了23
。如果您的时间是13
,14
或15
等等..hh
格式将失败。
而且由于您在方法中使用null
as a ,这意味着它默认使用。如果不是,您的方法甚至会抛出您的字符串和格式完全匹配,因为格式说明符在自定义日期和时间格式中具有特殊含义,例如;替换我当前文化的或提供的文化日期分隔符IFormatProvider
DateTime.ParseExact
CurrentCulture
DateSeparator
/
FormatException
"/"
你试过了吗
DateTime returnedDate = new DateTime();
DateTime.TryParse(timestr, out returnedDate);
请试试
string timestr = "1/20/2014 12:05:16 AM";
DateTime dt = new DateTime();
DateTime.TryParse(timestr, out dt);
M
- 月份,从 1 到 12。
“M”自定义格式说明符将月份表示为从 1 到 12 的数字(或者对于有 13 个月的日历,从 1 到 13)。单位数月份的格式不带前导零。
DateTime.ParseExact( timestr,"M/dd/yyyy hh:mm:ss tt",CultureInfo.InvariantCulture);
试试这个:
this.RequestDate = Convert.ToDateTime(this.DcmCreateDate).ToString("dd/MM/yyyy");