ZetCode

C# TimeZoneInfo

最后修改时间:2023 年 8 月 21 日

在本文中,我们将在 C# 中使用时区。

时区是使用同一时间的地理区域。 例如,在布拉迪斯拉发、布拉格或布达佩斯,使用中欧标准时间

TimeZoneInfo 是在 C# 中使用时区的主要类。 它是对有限的 TimeZone 的改进。 它允许我们枚举系统中可用的时区,检索操作系统定义的时区,在不同时区之间转换时间,或者序列化时区以供以后使用。

C# TimeZoneInfo.GetSystemTimeZones

TimeZoneInfo.GetSystemTimeZones 返回本地系统上所有可用时区的排序集合。

Program.cs
using System.Collections.ObjectModel;

ReadOnlyCollection<TimeZoneInfo> zones = TimeZoneInfo.GetSystemTimeZones();

foreach (TimeZoneInfo zone in zones)
{
    Console.WriteLine(zone.Id);
}

该程序检索并打印所有可用的系统时区。

$ dotnet run
Dateline Standard Time
UTC-11
Aleutian Standard Time
Hawaiian Standard Time
Marquesas Standard Time
Alaskan Standard Time
UTC-09
Pacific Standard Time (Mexico)
UTC-08
Pacific Standard Time
...

C# TimeZoneInfo.Local

TimeZoneInfo.Local 属性返回一个表示本地时区的 TimeZoneInfo 对象。

Program.cs
TimeZoneInfo local = TimeZoneInfo.Local;
Console.WriteLine(local.DisplayName);
Console.WriteLine(local.Id);
Console.WriteLine(local.DaylightName);
Console.WriteLine(local.SupportsDaylightSavingTime);

在该程序中,我们打印本地 TimeZoneInfo 对象的 DisplayNameIdDaylightNameSupportsDaylightSavingTime 属性。

$ dotnet run 
(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
Central Europe Standard Time
Central Europe Daylight Time
True

C# TimeZoneInfo.FindSystemTimeZoneById

TimeZoneInfo.FindSystemTimeZoneById 基于给定的标识符创建 TimeZoneInfo 的新实例。

Program.cs
TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");

Console.WriteLine(tzi.DisplayName);
Console.WriteLine(tzi.Id);
Console.WriteLine(tzi.StandardName);
Console.WriteLine(tzi.SupportsDaylightSavingTime);

在该程序中,我们为俄罗斯标准时间创建一个时区对象,并打印其基本属性。

$ dotnet run 
(UTC+03:00) Moscow, St. Petersburg
Russian Standard Time
Russia TZ 2 Standard Time
True

C# TimeZoneInfo.ConvertTime

TimeZoneInfo.ConvertTime 将时间转换为给定时区的时间。

Program.cs
Console.WriteLine(TimeZoneInfo.Local);
DateTime now = DateTime.Now;
Console.WriteLine(now);

Console.WriteLine("-----------------------------------");

TimeZoneInfo tzi = TimeZoneInfo.FindSystemTimeZoneById("Russian Standard Time");
Console.WriteLine(tzi.DisplayName);
DateTime target = TimeZoneInfo.ConvertTime(now, tzi);
Console.WriteLine(target);

我们获取当前的本地日期时间,并将其转换为俄罗斯标准时间。

$ dotnet run 
(UTC+01:00) Belgrade, Bratislava, Budapest, Ljubljana, Prague
8/21/2023 4:43:35 PM
-----------------------------------
(UTC+03:00) Moscow, St. Petersburg
8/21/2023 5:43:35 PM

来源

TimeZoneInfo 类 - 语言参考

在本文中,我们使用 TimeZoneInfo 在 C# 中使用了时区。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 自 2007 年以来,我一直在撰写编程文章。 迄今为止,我已经撰写了 1,400 多篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 C# 教程