简体   繁体   中英

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 . 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

I thought the TryParse would convert the dateString value to the required DateTime format. 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. In the example above I added that extra : after the year.

Also, you must use a CultureInfo which can understand your month name; 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

You can use TryParseExact method:

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 )
  • 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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