Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

DateTime parsing complicated strings C#

Tags:

c#

datetime

I am trying to parse date-strings to DateTime objects with the following format:

Tue, 30 Oct 2012 09:51:20 +0000

What I have tried so far is many different variants with DateTime.ParseExact().

I have tried:

DateTime.ParseExact("Mon, 29 Oct 2012 12:13:51 +0000", 
                    "ddd, dd MM yyyy hh':'mm':'ss zzz", 
                     CultureInfo.InvariantCulture);

With thousands different formats as second parameter, using null instead of InvarantCulture as third parameter etc etc. I can't get it to work. How should I parse a string like this?

Many thanks.

like image 705
Daniel Hallqvist Avatar asked Oct 30 '12 15:10

Daniel Hallqvist


2 Answers

How about

var s = "Tue, 30 Oct 2012 09:51:20 +0000";
DateTime.ParseExact(s, "ddd, dd MMM yyyy hh:mm:ss zzz", CultureInfo.InvariantCulture)

The month (Oct) is actually MMM, not MM, and the time (09:51:20) should be hh:mm:ss instead of hh':'mm':'ss.

like image 169
sloth Avatar answered Nov 08 '22 22:11

sloth


The correct parsing is

DateTime.ParseExact("Mon, 29 Oct 2012 12:13:51 +0000", "ddd, dd MMM yyyy HH:mm:ss K", CultureInfo.InvariantCulture);

Take a look here

like image 39
khellang Avatar answered Nov 08 '22 23:11

khellang