How can I parse the following line into a DateTime?

This is a very strange date from which I have never seen before returning from some API in JSON.

"Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)"

This results in the following error:

System.FormatException: String was not recognized as a valid DateTime.

This is understandable when using the following method for parsing:

DateTime.Parse(x.process_date.Value)

      

Does anyone deal with complex date formats who might know how to parse them?

+3


source to share


1 answer


You can use a method DateTime.ParseExact

(or DateTime.TryParseExact

, to cleanly handle parsing failures) to accomplish this. These methods allow you to explicitly specify the format string.

Something like this might work:

var dateString = "Tue Aug 04 2015 00:17:38 GMT+0000 (UTC)";
var format = "ddd MMM dd yyyy HH:mm:ss GMT+0000 (UTC)";

var parsed = DateTime.ParseExact(
    dateString, 
    format, 
    System.Globalization.CultureInfo.InvariantCulture);

      

Or, using TryParseExact

:

DateTime parsed;
if (DateTime.TryParseExact(
   dateString, 
   format, 
   System.Globalization.CultureInfo.InvariantCulture, 
   DateTimeStyles.None, 
   out parsed) 
{
   // parsing was successful
}
else
{
   // parsing failed
}

      



Here's a breakdown of the format string used here:

  • ddd

    - abbreviated name of the day of the week.
  • MMM

    - abbreviated name of the month.
  • dd

    - Day of the month, from 01 to 31 years.
  • yyyy

    - the year as a four-digit number.
  • HH:mm:ss

    - hour, using a 24-hour hour from 00 to 23; minute, from 00 to 59; and the second is from 0 to 59 (delimited :

    ).
  • GMT+0000 (UTC)

    - only static text that the format string accepts will always be present. This is quite fragile and could cause your parsing to fail if the API ever returns different text here. Consider truncating this text or using NodaTime , which offers great timezone support.

You may need to tweak this format string a little to suit your use - for example, it is not clear from your question whether you are using 12 hour time or 24 hour time.

For details on how to create a format string, see Custom Date and Time Strings on MSDN.

Alternatively, you can opt-out System.DateTime

in favor of NodaTime . I'm not very familiar with NodaTime, but great documentation is available as fooobar.com/questions/tagged / ... and on the NodaTime site.

+7


source







All Articles