简体   繁体   English

DateTime.TryParse无法按预期工作

[英]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 此外,您应该检查调用的结果,因为TryParseTryParseExact返回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: 提示:

  • If you use MMM , the month will be treated as if it is in 3 letter format (like Apr ) 如果你使用MMM ,月份将被视为3字母格式(如4月
  • If you use HH rather than hh it means the hour part is in 24-hour format, the it will not fail on parsing 15 as hour 如果你使用HH而不是hh它意味着小时部分是24小时格式,它将不会失败解析15小时

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

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