0

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);
Picrofo Software
  • 5,475
  • 3
  • 23
  • 37
Ben Cameron
  • 4,335
  • 6
  • 51
  • 77
  • Sounds like you need a mix of `DateTimeOffset` (which conserves the the offset, but not the time-zone) and a string that represents the timezone. Depending on the format of the string, you might be able to parse the timezone as well. – CodesInChaos Nov 06 '12 at 12:58
  • Dupe of [datetime.parse and making it work with a specific format](http://stackoverflow.com/questions/341175/datetime-parse-and-making-it-work-with-a-specific-format) ? – lstern Nov 06 '12 at 12:58
  • @lstern How is that a dupe? The issue here isn't just parsing the time, but the conserving offset&timezone as well. – CodesInChaos Nov 06 '12 at 12:59
  • 2
    @CodesInChaos Sorry. You can strip the zone name and use the "zzzz" token as shown [here](http://stackoverflow.com/a/241885/1020222) – lstern Nov 06 '12 at 13:04
  • TimeZone is tricky as not part of DataTime. Old link but still informative. http://msdn.microsoft.com/en-us/library/ms973825.aspx Another http://stackoverflow.com/questions/2532729/daylight-saving-time-and-timezone-best-practices – paparazzo Nov 06 '12 at 14:08

2 Answers2

3

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);
Rik
  • 28,507
  • 14
  • 48
  • 67
  • 1
    You'll need `DateTimeOffset` instead of `DateTime` to preserve the offset. And of course you need to store the timezone separately. – CodesInChaos Nov 06 '12 at 13:10
-1

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());
JSJ
  • 5,653
  • 3
  • 25
  • 32