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?

2
  • You could split the string for whitespaces and then use the constructor of DateTime to create your date. Commented Aug 16, 2012 at 13:50
  • have a look here or here or here Commented Aug 16, 2012 at 13:51

3 Answers 3

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

Sign up to request clarification or add additional context in comments.

7 Comments

You have missed the timezone portion. You can use K for this: "ddd MMM dd HH:mm:ss K yyyy"
@Oded: In my TimeZone ("India Standard Time", +5h:30m), this conversion is giving me 14/08/2012 00:34:51. Why is that so?
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: Yup. But one more ques. How to make sure that i also get 13/08/2012 15:04:51
You need to use the same culture - instead of the defaul or CultureInfo.InvariantCulture when formatting, try pt-Br.
|
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.

Comments

0

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

string-format-datetime

Custom Date and Time Format Strings

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.