Ben Cameron
Ben Cameron

Reputation: 4433

Parse date string .net

What's the best way to convert a string such as:

Mon Nov 05 2012 21:27:58 GMT+0000 (GMT Standard Time)

in to a DateTime in .NET? I want to retain as much of the date as possible, i.e the TimeZone.

I'm trying this but it loses the GMT:

DateTime.ParseExact(date.Substring(0, 24),
                             "ddd MMM d yyyy HH:mm:ss",
                             CultureInfo.InvariantCulture);

Upvotes: 0

Views: 628

Answers (2)

Rik
Rik

Reputation: 29243

It's not very robust, but it works for your example:

DateTimeOffset.ParseExact(date.Substring(0, 33) // remove time zone
                              .Remove(25,3)     // remove "GMT" before offset
                              ,"ddd MMM dd yyyy HH:mm:ss zzz"
                              ,System.Globalization.CultureInfo.InvariantCulture);

Upvotes: 3

JSJ
JSJ

Reputation: 5691

easy way to split the string and convert it into datetime using some formats. but what if some other formats comes to you.

try this one.

http://www.codeproject.com/Articles/33298/C-Date-Time-Parser

sample

string str = @"Your program recognizes string : 21 Jun 2010 04:20:19 -0430 blah blah.";
DateTimeRoutines.ParsedDateTime pdt;
if(str.TryParseDateTime(DateTimeRoutines.DateTimeFormat.USA_DATE, out pdt) && pdt.IsUtcOffsetFound) 
Console.WriteLine("UTC date&time was found: " + pdt.UtcDateTime.ToString());

Upvotes: -1

Related Questions