Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parse string to DateTime, sometimes adds 1 hour (timezone)

I'm having a problem when I need to parse a string to a datetime. Sometimes it adds an hour, sometimes it doesn't. Is there any reason why it does, because I don't wan't it to add an hour.

The first example does exactly what i need.

string s = "2016-01-28T20:59:00.000+01:00";            
DateTime ds = DateTime.Parse(s); //gives: 28/01/2016 20:59:00

The second example adds an hour, I wonder why.

string ss = "2016-05-27T10:38:00.000+01:00";
DateTime dss = DateTime.Parse(ss); //gives: 27/05/2016 11:38:00
like image 608
Dylan Slabbinck Avatar asked Jan 06 '23 18:01

Dylan Slabbinck


2 Answers

I strongly suspect this happens because of daylight saving time of your current timezone.

Looks like your timezone has UTC +01:00 in January but it has UTC +02:00 in May. That's why your second example adds one more hour since it has already 01:00 hour in it's offset part.

But instead of DateTime-since your string has UTC offset-I would parse it to DateTimeOffset.

DateTimeOffset ds = DateTimeOffset.Parse(s);

Now you have {28.01.2016 20:59:00 +01:00} and {27.05.2016 10:38:00 +01:00} as a DateTimeOffset values which is saved in theirs .DateTime and .Offset properties.

like image 189
Soner Gönül Avatar answered Jan 15 '23 23:01

Soner Gönül


The answer of Sonor Gönül is spot on. I want to add an example, that demonstrates the influence of the time zone, by converting your example times to a timezone with same offset but with different daylight saving time setting.

TimeZoneInfo noDaylightSavingTz = TimeZoneInfo.GetSystemTimeZones()
    .FirstOrDefault(x => x.SupportsDaylightSavingTime == false && x.BaseUtcOffset.Hours == 1);
string s = "2016-01-28T20:59:00.000+01:00";
DateTime ds = DateTime.Parse(s); //gives: 28/01/2016 20:59:00

string ss = "2016-05-27T10:38:00.000+01:00";
DateTime dss = DateTime.Parse(ss); //gives: 27/05/2016 11:38:00

if (noDaylightSavingTz != null)
{
    DateTime ds1 = TimeZoneInfo.ConvertTime(ds, noDaylightSavingTz);
    DateTime dss1 = TimeZoneInfo.ConvertTime(dss, noDaylightSavingTz);
}

ds1 and dss1 will contain the time values of your input, unless you don't have any compatible timezone installed for some reason.

like image 25
grek40 Avatar answered Jan 16 '23 00:01

grek40