1

Possible Duplicate:
Parse C# string to DateTime

I am facing a problem while converting string to DateTime.

I have the datetime string as

20120104073010.221-0700

I want to parse it to get DateTime object. Another thing, i am not sure if a . occures or not in the milliseconds part.

Is there any general way to parse such strings?

Community
  • 1
  • 1
Umer
  • 1,891
  • 5
  • 31
  • 43
  • 1
    question has been asked zillions of times here in SO: http://stackoverflow.com/questions/7580809/parse-c-sharp-string-to-datetime – Davide Piras Jan 12 '12 at 11:38
  • In that *particular* case, it might be worth handling the core time, the optional millis, and the timezone separately. I'd whack it into 3 pieces, personally. The core part is as Davide mentions; the rest is different, though – Marc Gravell Jan 12 '12 at 11:39

2 Answers2

7

You can use a custom Date and Time format string with ParseExact or TryParseExact.

Your date/time string looks like this format:

"yyyyMMddHHmmss.fffK"

DateTime dt = DateTime.ParseExact("20120104073010.221-0700", 
                                  "yyyyMMddHHmmss.fffK",
                                  CultureInfo.InvariantCulture);

ParseExact will throw an exception if it fails, so you may want to use TryParseExact that would return false on failing instead of throwing.

Oded
  • 489,969
  • 99
  • 883
  • 1,009
3

You might want to look at the DateTime.ParseExact method, which would allow you to specify a format string of the form "yyyyMMddHHmmss.fffzzz". This format string should handle the datetime string you have.

David M
  • 71,481
  • 13
  • 158
  • 186