UTC 日期时间转换为本地时间 [英] UTC datetime conversion to local time

查看:129
本文介绍了UTC 日期时间转换为本地时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将数据存储到 MySql 日期时间字段中,并且我总是在那里保存来自 C# 的 UTC 日期(使用someDate.ToUniversalTime()).

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

我在中欧时区.

我有一个日期是在 08.03.2016 保存为 2016-04-07 16:00:00(事件是在那个时间设置的),这个事件的正确当地时间是 2016-04-07 17:00:00,所以当时保存为GMT+1.我使用 someDate.ToLocalTime() 来获取正确的本地时间,并且效果很好.

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.

今天(4 月),由于 3 月底发生的 DayLight 事件,我们有 GMT+2 偏移量,现在 someDate.ToLocalTime() 显示我多 1 小时:2016-04-07 18:00:00 这是不正确的.

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.

如何普遍解决这个问题?我想保存 UTC 时间(就像现在一样),然后应用一些使用用户当前时区的系统转换,并始终从我保存的 UTC 日期返回正确的本地时间,关于当前 DayLightSaving 状态.它也应该返回 2016-04-07 17:00:00 而不是 2016-04-07 18:00:00

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

推荐答案

您的假设是错误的:中欧时区 2016-04-07 16:00 UTC 的有效本地时间始终为 2016-04-07 18:00 和从来没有 2016-04-07 17:00.您必须始终根据您查看的日期而不是当前日期计算 UTC 偏移量.

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

这篇关于UTC 日期时间转换为本地时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆