Reputation: 854
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
Upvotes: 5
Views: 3794
Reputation: 13438
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.
Upvotes: 1
Reputation: 98740
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.
Upvotes: 9