C# string to DateTime with timezone
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}
user1264255
Updated on July 09, 2022Comments
-
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 about 12 yearsHave a look here: link
-
Ramesh about 12 yearsAs per my knowledge your input should be "2012-04-20 10:10:00+02:00"
-
chaliasos about 12 years@user1264255 Yes, it will help you on your feature questions ;).
-
Luke Puplett over 8 yearsUseful MSDN link for roundtripping dates/times in .NET msdn.microsoft.com/en-us/library/bb882584(v=vs.110).aspx
-
-
user1264255 about 12 yearsthen i got the same when i just convert to datetime. result : // starttime = {20/04/2012 10:10:00} without my +0200
-
Red Bit about 12 yearsIt should be in +02:00 time zone already. Please check by toString("yyyy-MM-dd hh:mm:ss zzz")
-
user1264255 about 12 yearsThat's right, but i realy needed it in DateTime. V4Vendetta has given me the right solution. But still Thanks for your help :)
-
V4Vendetta about 12 yearsGlad ! you should attempt to mark as answers for all your questions which helped you and encourage others.
-
Keerigan almost 11 yearsSuch a useful thing to have!
-
jcaruso over 4 yearsThis does not do anything for timezone.