0

我不想每次更改夏令时时都必须更改配置。这是我目前正在做的,因为它使用“标准”时间而不起作用。

TimeZoneInfo timeZone = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time")
TimeZoneInfo.ConvertTimeToUtc(dateTime, timeZone); // This doesn't take into account that it's daylight savings...

是否有一种适合所有解决方案的尺寸。所以我可以给它一个日期时间和一个像“美国东海岸”这样的位置,它给我在UTC的时间?

4

2 回答 2

5

我之前通过使用映射表将时区 id 存储在数据库中来完成它。即包含结果的表TimeZone.GetSystemTimeZones()

您实际上不需要使用 TimeZoneInfo。FindSystemTimeZoneById()但是:您可以使用TimeZoneInfo.ConvertTimeBySystemTimeZoneId(). 此方法有一些采用DateTime值的重载,以及一些采用DateTimeOffset值的重载(这是更可取的,因为它们指定了一个明确的时间点)。

例如

TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.Now, "New Zealand Standard Time", "UTC")

使用系统时区 ID 而不是存储在数据库中的偏移量的真正好处是夏令时由TimeZoneInfo.ConvertTimeBySystemTimeZoneId.

这个 msdn 也可能对你有帮助>

http://msdn.microsoft.com/en-us/library/bb382058.aspx

于 2013-03-14T11:28:07.603 回答
1

您可以传递位置的 DateTime 和 TimeZone 并将提供的 DateTime 转换为 UTC

在此处检查此示例

       string DisplayName = "custom standard name here";//custom Standard Name to display eg: Kathmandu
       string StandardName = "custom standard name here"; // custom Standard Name eg: Asia/Kathamandu, Nepal
       string YourDate="27-03-2019 20:24:56"; // this DateTime doesn't contain any timeZone
       TimeSpan Offset = new TimeSpan(+5, 30, 00);// your TimeZone offset eg: timeZone of Nepal is +5:45
       TimeZoneInfo TimeZone = TimeZoneInfo.CreateCustomTimeZone(StandardName, Offset, DisplayName, StandardName);
       var RawDateTime = DateTime.SpecifyKind(DateTime.Parse(YourDate), DateTimeKind.Unspecified);// I all it RawDateTime Since it doesn't contain any TimeSpan
       DateTime UTCDateTime = TimeZoneInfo.ConvertTimeToUtc(RawDateTime, TimeZone);
       Console.WriteLine(UTCDateTime);
于 2019-03-27T15:13:59.770 回答