[英]DateTime.TryParse not working as expected
I am trying to get this date string 09 Apr 2015: 15:16:17 to display in this format 09/04/2015 15:16:17 . 我想用这个日期字符串09 Apr 2015:15:16:17以这种格式显示09/04/2015 15:16:17 。 This is what I have tried.
这就是我尝试过的。
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
DateTime.TryParse(dateString, out dateValue);
dtDateTime = dateValue;
This is the output 01/01/0001 00:00:00 这是输出01/01/0001 00:00:00
I thought the TryParse
would convert the dateString
value to the required DateTime
format. 我以为
TryParse
会将dateString
值转换为所需的DateTime
格式。 What am I doing wrong? 我究竟做错了什么?
You should go with this: 你应该这样做:
DateTime dtDateTime = new DateTime();
string dateString = "09 Apr 2015: 15:16:17";
DateTime dateValue;
if (DateTime.TryParseExact(dateString, @"dd MMM yyyy':' HH':'mm':'ss",
new CultureInfo("en-us"), DateTimeStyles.None, out dateValue))
dtDateTime = dateValue;
Using TryParseExact
you can provide a custom date format string to match your input date. 使用
TryParseExact
您可以提供自定义日期格式字符串以匹配您的输入日期。 In the example above I added that extra :
after the year. 在上面的例子中,我添加了额外的
:
一年之后。
Also, you must use a CultureInfo
which can understand your month name; 此外,您必须使用可以了解您的月份名称的
CultureInfo
; here I assumed you got an english formatted date. 在这里我假设你有一个英文格式的日期。
You need to specify the format since it's not a standard date format string: 您需要指定格式,因为它不是标准的日期格式字符串:
DateTime.TryParseExact(
dateString,
"dd MMM yyyy: HH:mm:ss",
CultureInfo.CurrentCulture,
DateTimeStyles.None,
out dateValue);
Also, you should check the result of the call since TryParse
and TryParseExact
return true
/ false
此外,您应该检查调用的结果,因为
TryParse
和TryParseExact
返回true
/ false
You can use TryParseExact
method: 您可以使用
TryParseExact
方法:
DateTime.TryParseExact(dateString, "dd MMM yyyy: HH:mm:ss",
System.Globalization.CultureInfo.InvariantCulture,
System.Globalization.DateTimeStyles.AllowWhiteSpaces,
out dtDateTime);
Tips: 提示:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.