Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# string to DateTime with timezone

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)

like image 510
user1264255 Avatar asked Apr 24 '12 07:04

user1264255


1 Answers

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)

like image 108
V4Vendetta Avatar answered Sep 19 '22 12:09

V4Vendetta