0

Possible Duplicate:
Parse string to DateTime in C#

I am getting date and time returned from an API as a string in the following format:

Mon Aug 13 15:04:51 -0400 2012

Does anyone have experience with how I can turn this into a DateTime?

Community
  • 1
  • 1
Thomas
  • 5,888
  • 7
  • 44
  • 83
  • You could split the string for whitespaces and then use the constructor of DateTime to create your date. – oopbase Aug 16 '12 at 13:50
  • have a look [here](http://stackoverflow.com/questions/5366285/parse-string-to-datetime-in-c-sharp) or [here](http://stackoverflow.com/questions/7580809/parse-c-sharp-string-to-datetime) or [here](http://stackoverflow.com/questions/7854529/unable-to-parse-datetime-from-a-string) – default Aug 16 '12 at 13:51

3 Answers3

3

How about

DateTime dt = DateTime.ParseExact("Mon Aug 13 15:04:51 -0400 2012",
                                  "ddd MMM dd HH:mm:ss K yyyy",
                                  CultureInfo.InvariantCulture)

You should read about Custom Date and Time Format Strings

Nikhil Agrawal
  • 47,018
  • 22
  • 121
  • 208
  • You have missed the timezone portion. You can use `K` for this: `"ddd MMM dd HH:mm:ss K yyyy"` – Oded Aug 16 '12 at 13:59
  • @Oded: In my TimeZone ("India Standard Time", +5h:30m), this conversion is giving me 14/08/2012 00:34:51. Why is that so? – Nikhil Agrawal Aug 16 '12 at 14:17
  • The time difference is `5:30 + 4 = 9:30`, so 9 and a half hours of difference. That's exactly the amount of time added to get your result. Make sense? In other words, `15:04` in central Brazil is the same point in time as `00:34` in India (not taking DST into account). – Oded Aug 16 '12 at 14:19
  • @Oded: Yup. But one more ques. How to make sure that i also get `13/08/2012 15:04:51` – Nikhil Agrawal Aug 16 '12 at 14:21
  • You need to use the same culture - instead of the defaul or `CultureInfo.InvariantCulture` when formatting, try `pt-Br`. – Oded Aug 16 '12 at 14:23
  • @Oded: I tried `DateTime.ParseExact("Mon Aug 13 15:04:51 -0400 2012", "ddd MMM dd HH:mm:ss K yyyy", new CultureInfo("pt-Br")).`. It returned error. – Nikhil Agrawal Aug 16 '12 at 14:49
  • Are you trying to parse it or display it? You need to use `ToString` to display it, using that culture. It will not parse because `Mon` and/or `Aug` are probably not valid shortcuts for Day/Month names in Portuguese. – Oded Aug 16 '12 at 14:55
2

Have a look at the DateTime.Parse method.

Or if you are not sure that the parsing will succeed, use the DateTime.TryParse method.

For unconventional date and time strings use the DateTime.ParseExact method.

victorvartan
  • 1,002
  • 2
  • 11
  • 31
0

Check these two links, I think they will be very useful to you:

string-format-datetime

Custom Date and Time Format Strings

Dante
  • 3,208
  • 9
  • 38
  • 56