当前时区时间

时间:2010-07-14 13:41:47

标签: c# timezone

我有不同的时区及其GMT和DST。示例:

TimeZoneId        |   GMT offset  |   DST offset  
                  |  1. Jan 2010  |  1. Jul 2010
--------------------------------------------------
America/Adak      |    -10.0      |     -9.0
America/Anchorage |     -9.0      |     -8.0
America/Anguilla  |     -4.0      |     -4.0
America/Antigua   |     -4.0      |     -4.0
America/Araguaina |     -3.0      |     -3.0

这个时区由Geoname提供。

如何在C#/ .NET中计算任何已知GMT和DST时区的当前时间?

更新:为了更好地指定,我提供“America / Antigua”,我需要“America / Antigua”中的当前时间。

3 个答案:

答案 0 :(得分:6)

TimeZoneInfo.ConvertTimeFromUtc(mytime, TimeZoneInfo.FindSystemTimeZoneById("Eastern Standard Time"));

答案 1 :(得分:2)

您提供的时区ID来自IANA时区数据库,即TZDB(又名Olson,又名tz)。它们不受.NET支持(尽管在Linux / Mac上运行的.NET Core可能会按照您的意愿运行)。

我的Noda Time项目确实支持他们。你会用:

var zoneId = "America/Antigua";
var zone = DateTimeZoneProviders.Tzdb[zoneId];
var now = SystemClock.Instance.GetCurrentInstant();
var zoned = now.InZone(zone);
Console.WriteLine(zoned);

明确使用SystemClock - 在实际代码中,我建议您接受IClock依赖注入以实现可测试性 - 在运行应用程序时注入SystemClock.Instance,但使用{{ 1}}用于测试。

展示FakeClock的替代等效代码:

ZonedClock

答案 2 :(得分:0)

private static ReadOnlyCollection<TimeZoneInfo> _timeZones = TimeZoneInfo.GetSystemTimeZones();

public static DateTime ToUsersTime(this DateTime utcDate, int timeZoneId)
{
    return TimeZoneInfo.ConvertTimeFromUtc(utcDate, timeZones[timeZoneId]);
}

使用TimeZoneInfo类(.NET 3.5 +)将UTC日期转换为用户日期的示例。

相关问题