且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UTC 日期时间转换为本地时间

更新时间:2023-02-03 17:19:58

您的假设是错误的:中欧时区 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