gpt4 book ai didi

C#冬令时到夏令时的DateTime转换

转载 作者:行者123 更新时间:2023-12-04 01:09:28 25 4
gpt4 key购买 nike

我收到这个错误:

The supplied DateTime represents an invalid time. For example, whenthe clock is adjusted forward, any time in the period that is skippedis invalid

当我尝试将时间 2020-03-29 02:30 从东欧时间 (GMT+2) 转换为 UTC 时间时。

根据 this site芬兰的时钟应该在 03:00 更改,这意味着时间 02:30 应该可以转换为 UTC。

但是当我运行下面的代码时,抛出了一个异常。

var timezoneMap = TimeZoneInfo.GetSystemTimeZones().ToDictionary(x => x.Id, x => x);
var timezoneInfo = timezoneMap["E. Europe Standard Time"];

var localTime1 = DateTime.SpecifyKind(new DateTime(2020, 12, 15, 0, 0, 0), DateTimeKind.Unspecified);
var localTime2 = DateTime.SpecifyKind(new DateTime(2020, 3, 29, 2, 30, 0), DateTimeKind.Unspecified);

var utc1 = TimeZoneInfo.ConvertTimeToUtc(localTime1, timezoneInfo); // 2020-12-14 22:00 correct
var utc2 = TimeZoneInfo.ConvertTimeToUtc(localTime2, timezoneInfo); // throws exception

第二次转换有什么问题,为什么会出现异常?

最佳答案

您正在查看的网站使用 IANA time zone data ,我认为这是准确的。

但是您的代码使用了 Windows 时区数据库,在这种情况下,它看起来有差异……它似乎认为转换是在 UTC 午夜而不是 UTC 凌晨 1 点。下面是演示这一点的代码:

using System;
using System.Globalization;

class Program
{
static void Main()
{
var zone = TimeZoneInfo.FindSystemTimeZoneById("E. Europe Standard Time");

// Start at 2020-03-28T23:00Z - definitely before the transition
var utc = new DateTime(2020, 3, 28, 23, 0, 0, DateTimeKind.Utc);
for (int i = 0; i < 8; i++)
{
var local = TimeZoneInfo.ConvertTime(utc, zone);
Console.WriteLine($"{utc:yyyy-MM-dd HH:mm} UTC => {local:yyyy-MM-dd HH:mm} local");
utc = utc.AddMinutes(30);
}
}
}

输出(带注释):

2020-03-28 23:00 UTC => 2020-03-29 01:00 local
2020-03-28 23:30 UTC => 2020-03-29 01:30 local
2020-03-29 00:00 UTC => 2020-03-29 03:00 local <= Note the change here, at midnight UTC
2020-03-29 00:30 UTC => 2020-03-29 03:30 local
2020-03-29 01:00 UTC => 2020-03-29 04:00 local
2020-03-29 01:30 UTC => 2020-03-29 04:30 local
2020-03-29 02:00 UTC => 2020-03-29 05:00 local
2020-03-29 02:30 UTC => 2020-03-29 05:30 local

当前的 IANA 数据肯定确实说世界标准时间凌晨 1 点,如 this line of the rules 所示。 .所以我相信该网站正确地解释了数据,这只是 Windows 时区数据库“不同”的问题(而且我怀疑是不正确的)。

关于C#冬令时到夏令时的DateTime转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65327442/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com