Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I parse the following string into DateTime?

Tags:

c#

This is a very strange date fromat I have never seen before coming back from some API in JSON.

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

That is generating the following error:

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

Which is understandable when using the following method to parse:

DateTime.Parse(x.process_date.Value)

Anyone dealt with complex date formats that may know how to parse that?

like image 234
Louie Bacaj Avatar asked Dec 05 '25 17:12

Louie Bacaj


1 Answers

You can use the DateTime.ParseExact method (or DateTime.TryParseExact, to cleanly handle parsing failures) to accomplish this. These methods allow you to explicitly specify the format string.

Something like this could 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 - The abbreviated name of the day of the week.
  • MMM - The abbreviated name of the month.
  • dd - The day of the month, from 01 through 31.
  • yyyy - The year as a four-digit number.
  • HH:mm:ss - The hour, using a 24-hour clock from 00 to 23; the minute, from 00 through 59; and the second, from 0 through 59 (delimited by : characters).
  • GMT+0000 (UTC) - just static text that the format string assumes will always be present. This is pretty brittle 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 support for time zones.

You might need to tweak this format string slightly to your usage -- for example, it wasn't clear from your question whether or not you are using a 12-hour clock or a 24-hour clock.

For more information on how to build a format string, see Custom Date and Time Format Strings on MSDN.

Alternatively, you could eschew using System.DateTime in favor of NodaTime. I'm less familiar with NodaTime myself, but great documentation is available both here on StackOverflow and on NodaTime's site.

like image 161
Donut Avatar answered Dec 08 '25 05:12

Donut



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!