Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse DateTime from string c#

Tags:

c#

datetime

I have date that I get from incoming API call: Wed, 6 Mar 2019 14:39:49 +0300

I need to parse this string to DateTime. For this I'm using the following code:

DateTime.ParseExact("Wed, 6 Mar 2019 14:39:49 +0300", 
                     new string[] { "ddd, dd MMM yyyy HH:mm:ss zzzz" },
                     CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

But as a result I have error:

String 'Wed, 6 Mar 2019 14:39:49 +0300' was not recognized as a valid DateTime.

What am I doing wrong? How can I resolve this?

like image 614
A. Gladkiy Avatar asked Dec 03 '22 18:12

A. Gladkiy


1 Answers

I see 2 things;

  1. You should use d specifier instead of dd specifier since your single digit day number does not have a leading zero.
  2. There is no zzzz as a custom format specifier. You should use zzz specifier instead.

DateTime.ParseExact("Wed, 6 Mar 2019 14:39:49 +0300", 
                     new string[] { "ddd, d MMM yyyy HH:mm:ss zzz" },
                     CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

But honestly, if your strings have a UTC Offset value, I would suggest parse it to DateTimeOffset instead since a DateTime instance does not have offset part and using zzz specifiers is not recomended as stated on MSDN.

With DateTime values, the "zzz" custom format specifier represents the signed offset of the local operating system's time zone from UTC, measured in hours and minutes. It does not reflect the value of an instance's DateTime.Kind property. For this reason, the "zzz" format specifier is not recommended for use with DateTime values.

To parse DateTimeOffset,

DateTimeOffset.ParseExact("Wed, 6 Mar 2019 14:39:49 +0300", 
                           new string[] { "ddd, d MMM yyyy HH:mm:ss zzz" },
                           CultureInfo.InvariantCulture, DateTimeStyles.AdjustToUniversal);

Now you can use it's .DateTime and/or .Offset properties separately if you want.

like image 177
Soner Gönül Avatar answered Dec 22 '22 04:12

Soner Gönül