17

I want to format the string : "2012-04-20 10:10:00+0200" to a dateTime with this format. so I think it must be "yyyy-MM-dd hh:mm:ss zzz"?

when I tried this

   // starttime =  {20/04/2012 10:10:00} without my +0200!
DateTime starttime = Convert.ToDateTime("2012-04-20 10:10:00+0200",CultureInfo.CurrentCulture);
// And this gave me a format exception : {System.FormatException: String was not recognized as a valid DateTime.
        DateTime result = DateTime.ParseExact("2012-04-20 10:10:00+0200", "yyyy-MM-dd hh:mm:ss zzz", CultureInfo.InvariantCulture);

SOLUTION GIVEN BY "V4Vendetta" :

You should try using DateTimeOffset instead of the DateTime

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

Here you get the Offset (2 hrs) too which could be computed with your DateTime (10:10) value and get your desired out put (result.DateTime + result.Offset)

4
  • 1
    Have a look here: link Commented Apr 24, 2012 at 7:22
  • 1
    As per my knowledge your input should be "2012-04-20 10:10:00+02:00" Commented Apr 24, 2012 at 7:23
  • @user1264255 Yes, it will help you on your feature questions ;). Commented Apr 24, 2012 at 8:58
  • Useful MSDN link for roundtripping dates/times in .NET msdn.microsoft.com/en-us/library/bb882584(v=vs.110).aspx Commented Oct 12, 2015 at 11:50

4 Answers 4

33

You should try using DateTimeOffset instead of the DateTime

DateTimeOffset result = DateTimeOffset.Parse("2012-04-20 10:10:00+0200",CultureInfo.InvariantCulture);

Here you get the Offset (2 hrs) too which could be computed with your DateTime (10:10) value and get your desired out put (result.DateTime + result.Offset)

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

2 Comments

Glad ! you should attempt to mark as answers for all your questions which helped you and encourage others.
Such a useful thing to have!
2

use "2012-04-20 10:10:00 +02:00" instead of " "2012-04-20 10:10:00+0200"

3 Comments

then i got the same when i just convert to datetime. result : // starttime = {20/04/2012 10:10:00} without my +0200
It should be in +02:00 time zone already. Please check by toString("yyyy-MM-dd hh:mm:ss zzz")
That's right, but i realy needed it in DateTime. V4Vendetta has given me the right solution. But still Thanks for your help :)
1

The MSDN article here seems to have exactly what you're looking for. Per said article, you should be using {0:MM/dd/yy H:mm:ss zzz}

Comments

-1

Try this:

DateTime datetime = DateTime.ParseExact("10/10/2009 12:00:00", "MM/dd/yyyy hh:mm:ss", System.Globalization.CultureInfo.CurrentCulture);

1 Comment

This does not do anything for timezone.

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.