简体   繁体   中英

UTC datetime conversion to local time

I store data into MySql datetime field and I was saving there always UTC date from C# (using someDate.ToUniversalTime() ).

I am in Central European timezone.

I have one date that was saved on 08.03.2016 as 2016-04-07 16:00:00 (event was set in the future at that time) and correct local time for this event was 2016-04-07 17:00:00, so it was saved as GMT+1 at that time. I used someDate.ToLocalTime() to get correct local time and it worked well.

Today (in April), because of DayLight event that occured at the end of March we have GMT+2 offset and now someDate.ToLocalTime() shows me 1 hour more: 2016-04-07 18:00:00 which is not correct.

How to solve this universally? I want to save UTC time (as now) and then to apply some system conversion that use user's current timezone and always return correct local time from my saved UTC date regarding the current DayLightSaving status. It should also return 2016-04-07 17:00:00 and not 2016-04-07 18:00:00

Your assumption is wrong: The valid localtime for 2016-04-07 16:00 UTC in Central Europe Timezone is always 2016-04-07 18:00 and never was 2016-04-07 17:00. You must calculate the UTC offset always with respect to the date you are looking at and not the current date.

Try the following code. It will always print the same values, regardless of your current date (ie whether you are currently in daylightsaving or not)

var dt1 = new DateTime(2016, 3, 1, 15, 0, 0, DateTimeKind.Utc);
var dt2 = new DateTime(2016, 5, 1, 15, 0, 0, DateTimeKind.Utc);

var s1 = dt1.ToLocalTime().ToString("s");
var s2 = dt2.ToLocalTime().ToString("s");

Console.WriteLine(s1);  //prints 2016-03-01T16:00:00  because GMT+1 at that date
Console.WriteLine(s2);  //prints 2016-05-01T17:00:00  because GMT+2 at that date

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM