【问题标题】:Get the date of a time by different timezone?通过不同的时区获取时间的日期?
【发布时间】:2020-01-17 23:09:26
【问题描述】:

以下代码将按时区返回正确的日期。 TimeZoneInfo.ConvertTimeBySystemTimeZoneId 在我的情况下还不够快。这是一种更快的方法吗?

// Return the date part of t by tz
DateTime GetDateByTZ(DateTimeOffset t, string tz)
{
    return TimeZoneInfo.ConvertTimeBySystemTimeZoneId(t, tz).Date;
}

var t1 = DateTimeOffset.Parse("1/17/2020 21:00 -5");
GetDateByTZ(t1, 'GMT Standard Time') // returns 2020-1-18

我需要一个超级快的GetDateByTZ 版本。

我发现使用 t.AddHours(...).Date 快得多,但我需要维护一个小时偏移量查找表,以及夏令时更改的逻辑 (https://en.wikipedia.org/wiki/Daylight_saving_time)。

例如,如果我在伦敦,我可以拨打DateTime.Now.AddHours(-5).Date 以获取“东部标准时间”的日期。但是,我需要在夏天将 -5 更改为 -4。

【问题讨论】:

  • 很困惑,你有什么问题
  • 为什么觉得不够快?您运行了哪些基准测试?
  • 如果您遇到复杂的日期/时区问题,Noda Time (nodatime.org) 通常是解决方案的一部分
  • 另外,您使用的是哪个 .NET 运行时?您每次传递的时区 ID 是相同的,还是不同的?
  • @MattJohnson-Pint,10M 调用大约需要 2 秒。

标签: c# datetime timezone


【解决方案1】:

不确定我们是否从您那里获得了足够的信息(请参阅有关您的问题的 cmets),但我会指出:

DateTimeOffset result = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(dateTimeOffset, timeZoneId)

...等价于:

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById(timeZoneId);
DateTimeOffset result = TimeZoneInfo.ConvertTime(dateTimeOffset, tzi);

因此,如果您反复使用同一个区域,您可以通过查找TimeZoneInfo 对象一次并保留它以在将来的转换中重复使用,从而获得稍好的结果。

我说只是稍微快一点,因为FindSystemTimeZoneByIdConvertTimeBySystemTimeZoneId 都使用内部缓存。因此,您不会减少分配,只是减少从缓存中查找项目所需的时间。

【讨论】:

  • 老实说,这 still 对我来说似乎是一个微优化。在现实生活中,我们是否需要更快的解决方案来应对这种情况?也许一些学术/科学研究?嗯,我不知道。在我看来,OP 应该首先race his/her horses 知道哪种方式更快:)
猜你喜欢
  • 1970-01-01
  • 2017-12-18
  • 1970-01-01
  • 2012-09-10
  • 2013-07-13
  • 2020-07-08
  • 2018-09-08
  • 2020-03-17
  • 1970-01-01
相关资源
最近更新 更多