Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ConvertTimeToUtc is always off by one hour

I am facing issue while converting datetime to UTC. User enters date in mydate in the webform, which we need to convert in UTC and store it in DB.

User also selects timezone from the list which is stored in selectedTimeZone variable. So we have to convert mydate from selectedTimeZone to UTC.

TimeZoneInfo.ConvertTimeToUtc(mydate, selectedTimeZone);

Example#1 :

If mydate = 05/02/2016 09:00 AM and selectedTimeZone = EST (-5:00) then TimeZoneInfo.ConvertTimeToUtc(mydate, selectedTimeZone) returns 05/02/2016 13:00

which is off by one hour

Example#2

If mydate = 05/02/2016 09:00 AM and selectedTimeZone = IST (indian standard time) (+5:30) then TimeZoneInfo.ConvertTimeToUtc(mydate, selectedTimeZone) returns 05/02/2016 03:30

which is correct

There are multiple examples like this.

What is the issue?

Edit:

I don't need to convert user input to DateTime as .net does it, we are getting mydate in mvc action method parameter.

I tried it by setting local timezone of a machine to UTC, London, IST..... but it makes no difference to the output.

like image 622
Anil Purswani Avatar asked Feb 07 '23 04:02

Anil Purswani


1 Answers

It seems adjustment rules for given timezone play their role here. Take the following code:

var mydate = new DateTime(2016, 05, 02, 9, 0, 0);            
var selectedTimeZone = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");
var dstRule = selectedTimeZone.GetAdjustmentRules().FirstOrDefault(c => c.DateStart < mydate && c.DateEnd > mydate);

There is just one adjustment rule for EST timezone which is active at given time (it is active starting at 2007 year), and this rule works from second Sunday of March to first Sunday of November every year, adjusting time by one hour during that period. That is why you observe that behaviour. If you try to convert date outside of period for this rule (say, in February) - you will get what you would expect.

So to clarify: EST timezone has base offset of UTC-5, but because of daylight savings becomes UTC-4 during summer, and because your time is "summer" - .NET actually correctly converts that to UTC, it's not "off by one hour".

like image 102
Evk Avatar answered Feb 12 '23 10:02

Evk