【问题标题】:How can I create a new instance of DateTime in specific time zone?如何在特定时区创建 DateTime 的新实例?
【发布时间】:2025-12-21 17:55:11
【问题描述】:

给定一个特定的 TimeZoneInfo 实例,我如何在指定的时区创建一个新的 DateTime 实例?例如,如果我有:

var tz = TimeZoneInfo.FindSystemTimeZoneById("US Eastern Standard Time");
var date = new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Unspecified);
Console.WriteLine(TimeZoneInfo.ConvertTime(date, tz));

无论我定义什么 DateTimeKind(UTC、本地或未指定),我总是得到 12/31/2016 7:00:00 PM。

如何声明一个新的 DateTime,即美国东部标准时间 2017 年 1 月 1 日 0:00:00?

【问题讨论】:

  • 您能解释一下您的预期输出吗?是否要将DateTime特定时区转换为当地时间?
  • @FedericoDipuma 不,我想为特定时区定义一个新的特定日期时间。例如,我想要 2017 年 1 月 1 日(美国东部标准时间)的 DateTime 实例。我不想依赖本地服务器时间,因为服务器可能不在我的客户端所在的位置。所以我为每个客户端保存了 TimeZoneInfo,我想基于它来实例化时间。
  • DateTime 仅区分本地时间和 UTC 时间,其中没有时区特定信息。您要么必须从您的时区转换为 UTC(如果需要,然后再转换为本地时间)或使用 DateTimeOffset,即使它没有时区信息,它至少具有与 UTC 存储的内置偏移量.另请注意,使用客户端时区存储时间戳几乎总是一个坏主意,最好存储 UTC 日期/时间,然后在可视化时在客户端内部进行时区转换。

标签: c# datetime


【解决方案1】:

您可以使用 TimeZoneInfo 检索您的区域

你可以在这里找到timezones

var zn = TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time");

要表示您使用的是当地东部标准时间,请使用 DateTimeOffset 结构而不是 DateTime

DateTimeOffset dateTimeOffset = new DateTimeOffset(new DateTime(2017, 1, 1, 0, 0, 0, DateTimeKind.Unspecified), zn.BaseUtcOffset); 

为什么DateTimeOffset

DateTimeOffset is a representation of instantaneous time (also known as absolute time).

【讨论】:

  • 我需要使用 TimeZoneInfo 实例,因为我可以使用它,你能告诉我 TimeSpan 如何映射到 TimeZoneInfo 吗?您只是手动编码 -5 时差。
  • @Marko 你的意思是什么,因为我可以使用你的意思是动态检索区域
  • 这对我来说是正确的答案,因为它通过 dateTimeOffset.DateTime 为我提供了 DateTime 实例,并且还通过 dateTimeOffset .Offset 为我提供了 -5 的偏移量。
【解决方案2】:

您可以使用 timezoneID 来指定要创建日期时间对象的时区。

TimeZoneInfo tzone= TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard 
Time");
DateTime dt = DateTime.Now();

稍后您只需将日期时间转换为所需的时区。

var datetime2 = TimeZoneInfo.ConvertTimeFromUtc(dt , tzone);

这是您可以找到所有时区 ID 的链接。 TimeZoneIDs

谢谢,希望对你有帮助。

【讨论】:

  • DateTime.Now 将使用系统当前时区设置提供时间。我想你的意思是DateTime.UtcNow