65.9K
CodeProject 正在变化。 阅读更多。
Home

时区类

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (16投票s)

2007年9月12日

CPOL

3分钟阅读

viewsIcon

147985

downloadIcon

4528

TimeZoneInfo 类为系统上的任何时区提供属性和方法。

引言

这又是另一个时区类,它允许您完全访问和使用不同的时区。 众所周知,.NET(直到 Framework 2)的时区类用处不大,因为它只提供与当前时区相关的对象。 因此,我决定创建一个名为 TimeZoneInfo 的时区类,它可以为我们提供有关其他时区的信息和方法。

TimeZoneInfo 类进行纯 .NET 实现,并且仅使用一个 API 方法来设置当前系统计算机的 TimeZone。 这意味着与某些其他时区实现相比,99% 是托管代码。

背景

我见过许多时区类,但几乎所有类都缺少一些功能或功能实现不正确。 时区类乍一看似乎很简单,但相信我,这有点棘手。 TimeZoneInfo 类基于 Windows 注册表信息,位于键 HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\Time Zones 下,因此注册表包含来自 Microsoft 的最新更新至关重要。
该类提供了时区的所有信息和功能。 例如,它提供时区的夏令时日期、当前 UtcOffset、当前时间、当前系统时区等。

使用的 API 函数

名称 目的
SetTimeZoneInformation 设置当前系统时区

属性

名称 描述
DisplayName 获取时区的显示名称
DaylightName 获取时区的夏令时名称
StandardName 获取时区的标准名称
CurrentTime 获取时区的当前日期和时间
CurrentUtcOffset 获取时区的当前 UTC(协调世界时)偏移量
CurrentTimeZone 获取或设置此计算机系统的当前时区
StandardUtcOffset 获取时区的标准 UTC(协调世界时)偏移量
ID 获取时区的 ID

方法

名称 描述 参数 返回值
GetTimeZones 获取系统上所有时区的数组 TimeZoneInfo 数组
FromStandardName 从标准名称获取一个 TimeZoneInfo.Object 标准名称 (string) TimeZoneInfo
FromId 从 ID 获取一个 TimeZoneInfo.Object ID (string) TimeZoneInfo
GetDaylightChanges 返回特定年份的夏令时 年份 (Integer) DaylightTime
IsDaylightSavingTime 返回一个值,该值指示此特定时区是否在夏令时期间 True/False (Boolean)
刷新 刷新时区对象的信息
Sort 根据标准 UTC 偏移量或显示名称对 List(Of TimeZoneInfo) 对象/TimeZoneInfo 数组中的元素进行排序 tzInfos (List(Of TimeZoneInfo)/TimeZoneInfo 数组
ToString 返回一个 System.String,它表示当前 TimeZoneInfo 对象 none 显示名称 (String)
Equals 确定指定的 System.Object 是否等于当前的 System.Object obj (Object) True/False (Boolean)

使用代码

有关更多示例,请查看演示项目。

'Get all the time zones on the system and show them in a ListBox control

Me.ListBox1.DataSource = TimeZoneInfo.GetTimeZones

Dim tzInfo As TimeZoneInfo 
'Create new instance of a TimeZoneInfo for a specific time zone 

tzInfo = New TimeZoneInfo("Pacific Standard Time") 
'Or tzInfo = TimeZoneInfo.FromStandardName("Pacific Standard Time") 

'Get the current UtcOffset of the time zone 

Dim utcOffset As TimeSpan = tzInfo.CurrentUtcOffset 
'Get the current time of the time zone 

Dim time As DateTime = tzInfo.CurrentTime 
'Get a value specifying if it is a daylight saving time 

'currently for the time zone 

Dim isDaylight As Boolean = tzInfo.IsDaylightSavingTime 
'Get daylight changes for the year 2007 of the time zone 

Dim dStart, dEnd As DateTime 
Dim dt As System.Globalization.DaylightTime 
dt = tzInfo.GetDaylightChanges(2007) 
dStart = dt.Start 
dEnd = dt.End 
'And much more 

'... 

'... 

系统要求

  • Windows NT/2000/XP(仅在 XP 上测试)
  • Framework 2.0

TimeZoneInfo 信息

历史

  • 2007 年 9 月 12 日 - 发布原始版本
  • 2007 年 9 月 17 日 -(对 Sort 功能进行了一些内部小更改以进行优化)
© . All rights reserved.