C# string to DateTime with timezone

31,859

Solution 1

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)

Solution 2

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

Solution 3

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}

Share:
31,859
user1264255
Author by

user1264255

Updated on July 09, 2022

Comments

  • user1264255
    user1264255 almost 2 years

    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)

    • Willem
      Willem about 12 years
      Have a look here: link
    • Ramesh
      Ramesh about 12 years
      As per my knowledge your input should be "2012-04-20 10:10:00+02:00"
    • chaliasos
      chaliasos about 12 years
      @user1264255 Yes, it will help you on your feature questions ;).
    • Luke Puplett
      Luke Puplett over 8 years
      Useful MSDN link for roundtripping dates/times in .NET msdn.microsoft.com/en-us/library/bb882584(v=vs.110).aspx
  • user1264255
    user1264255 about 12 years
    then i got the same when i just convert to datetime. result : // starttime = {20/04/2012 10:10:00} without my +0200
  • Red Bit
    Red Bit about 12 years
    It should be in +02:00 time zone already. Please check by toString("yyyy-MM-dd hh:mm:ss zzz")
  • user1264255
    user1264255 about 12 years
    That's right, but i realy needed it in DateTime. V4Vendetta has given me the right solution. But still Thanks for your help :)
  • V4Vendetta
    V4Vendetta about 12 years
    Glad ! you should attempt to mark as answers for all your questions which helped you and encourage others.
  • Keerigan
    Keerigan almost 11 years
    Such a useful thing to have!
  • jcaruso
    jcaruso over 4 years
    This does not do anything for timezone.