【发布时间】:2016-11-07 22:29:31
【问题描述】:
我正在尝试编写一个函数,该函数将 (1) 在任何时区的机器上运行,(2) 计算两个日期之间的小时数,以及 (3) 将给定时区的 DST 设置放入帐户...
这似乎很容易,但我似乎无法弄清楚。
我正在生成其他时区的工作时间表。因此,例如,昨天(2016 年 11 月 6 日)在纽约,我需要生成 25 小时的时间表。今天(2016 年 11 月 7 日)我只需要生成 24 小时的时间表。明年三月,会有一天需要23小时。
我认为这是我的签名,但我想我可能需要一个 string TimeZoneId 参数。
public double GetScheduledHours(DateTime begin, DateTime end) {}
我从这里开始:
// incorrectly outputs 24
Console.WriteLine((new DateTime(2016, 11, 7) - new DateTime(2016, 11, 6)).TotalHours);
接下来我尝试了这个,但取得了短暂的成功:
// correctly outputs 25 on a machine whose local time zone is "Eastern Standard Time"
// incorrectly outputs 24 on dotnetfiddle whose local time zone is "Coordinated Universal Time"
var ticks = (new DateTime(2016, 11, 7).ToUniversalTime().Ticks - new DateTime(2016, 11, 6).ToUniversalTime().Ticks;
Console.WriteLine(ticks / 10000 / 1000 / 60 / 60 + " hours");
我尝试使用 DateTimeOffset 无济于事,还发现了一些奇怪的行为......
// on a machine whose local time zone is Easter Standard Time,
// if you store the DateTime inside of a DateTimeOffset, simple subtraction works fine
var pacificTz = TimeZoneInfo.FindSystemTimeZoneById("Pacific Standard Time");
DateTime pst6thAsDateTime = pst6th.DateTime;
DateTime pst7thAsDateTime = pst7th.DateTime;
DateTimeOffset pst6thAsDateTimeOffset = pst6th.DateTime;
DateTimeOffset pst7thAsDateTimeOffset = pst7th.DateTime;
// incorrectly outputs 24
Console.WriteLine((pst7thAsDateTime - pst6thAsDateTime).TotalHours);
// correctly outputs 25
// also incorrectly outputs 24 on a machine whose local time zone is not "Eastern Standard Time"
Console.WriteLine((pst7thAsDateTimeOffset - pst6thAsDateTimeOffset).TotalHours);
一些代码的摆弄...如果您在本地时区为“东部标准时间”的机器上运行此代码,则只有 2 个失败。
【问题讨论】:
-
您还必须记住,纽约将在 11 月 6 日更改 DST,而欧洲则在 10 月 30 日更改。
标签: c# datetime datetimeoffset