当两种日期类型都是 DateTimeOffset 时,将日期从一个时区转换为另一个时区

Converting date from one timezone to another when both date types are DateTimeOffset

我似乎经常需要在 DateTimeOffset 中将 DateTimeOffset 值转换为另一个时区。最令人头疼的是 TimeZoneInfo class 转换方法 returns DateTime,所以当我将数据转换为 DateTimeOffset 类型时,我最终不得不再次转换数据。

为了克服这个问题,我想出了一个 DateTimeOffset 的扩展方法:

这必须存在于 class.

public static DateTimeOffset ToNewTimeZone(this DateTimeOffset value, string timeZone)
{
    value = value.UtcDateTime;
    TimeZoneInfo tzObject = TimeZoneInfo.FindSystemTimeZoneById(timeZone);
    //Using the GetUtcOffset means that the TimeZoneInfo class is responsible for calculating the Daylight savings time.
    DateTimeOffset ret = value.ToOffset(tzObject.GetUtcOffset(value));
    return ret;
}

它在我提出的每个测试用例下都工作得非常好,但对我来说似乎不够优雅。这通常表明已经有更好的解决方案。不过我还没找到。

我创建了一个 .NET Fiddle 来展示我的作品。 https://dotnetfiddle.net/LLl1Za

第 42 和 43 行根据我上面的其他实验突出显示了这段代码。

为了让我们有上下文,我不能更改数据库以仅以 UTC 格式存储数据,而只能更改客户端屏幕的区域。该项目太大太广泛,现在无法进行此更改。有很多文章讨论其他时区处理问题,但不是这个特定场景。

有更好的方法吗?

我看不出你应该自己实施它的理由。您应该使用 TimeZoneInfo.ConvertTime() 更改 DateTimeOffset.

的时区

请参考https://msdn.microsoft.com/en-us/library/bb396765%28v=vs.110%29.aspx