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?

2
  • 1
    question has been asked zillions of times here in SO: stackoverflow.com/questions/7580809/… Commented Jan 12, 2012 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 Commented Jan 12, 2012 at 11:39

2 Answers 2

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.

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

Comments

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.

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.