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);
5
  • 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. Commented Nov 6, 2012 at 12:58
  • Dupe of datetime.parse and making it work with a specific format ? Commented Nov 6, 2012 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. Commented Nov 6, 2012 at 12:59
  • 2
    @CodesInChaos Sorry. You can strip the zone name and use the "zzzz" token as shown here Commented Nov 6, 2012 at 13:04
  • TimeZone is tricky as not part of DataTime. Old link but still informative. msdn.microsoft.com/en-us/library/ms973825.aspx Another stackoverflow.com/questions/2532729/… Commented Nov 6, 2012 at 14:08

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

1 Comment

You'll need DateTimeOffset instead of DateTime to preserve the offset. And of course you need to store the timezone separately.
-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());

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.