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

在 Windows 下 .NET 中使用时区

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.89/5 (5投票s)

2008年6月6日

CPOL

1分钟阅读

viewsIcon

45062

downloadIcon

519

本文档描述了如何在 .NET 2.0 中进行任意时区之间的转换。

引言

.NET 2.0 中的时区处理仅限于在 UTC 和本地时间(通常是服务器时间)之间进行转换。 然而,为了正确地向不同地区的用户显示 DateTime,尤其是在 Web 应用程序中,你需要能够将 DateTime 在 UTC(你应该始终将数据存储在数据库中的格式)和目标时区之间进行转换。

背景

源代码包含一个库(基本上是一个类)和一个示例应用程序,演示了如何使用该库。

该库读取注册表以获取时区名称和基本信息,并使用 Interop 访问 Windows 系统调用,以在不同的时区之间进行转换。

使用代码

以下行摘自示例应用程序

// list all time zones
TimeZoneInformation[] arrTzi = TimeZoneInformation.EnumZones();
foreach (TimeZoneInformation tzi in arrTzi)
{
    Console.Write("name: " + tzi.Name);
    Console.WriteLine(" --- now: " + tzi.FromUniversalTime(dt));
}

TimeZoneInformation 类的每个实例都具有以下有用的属性:NameDisplayNameIndexBias(相对于 UTC)、DaylightBiasDaylightNameStandardBiasStandardName

时区之间的转换就像这样简单

TimeZoneInformation tziLocal = TimeZoneInformation.CurrentTimeZone;
TimeZoneInformation tziRemote = TimeZoneInformation.FromIndex(10);
// convert local time to UTC (could be abbreviated as DateTime.UtcNow)
DateTime dt = tziLocal.ToUniversalTime(DateTime.Now);
DateTime dt2 = tziRemote.FromUniversalTime(dt);

关注点

我注意到时区名称在 Windows 更新时会发生变化,因此你不希望依赖它们。 我希望 Index 属性不会改变。

致谢

我从互联网上找到了我代码的基础,但我不记得具体在哪里了(大约两年前)。 如果您是借用我代码片段的人,请给我发邮件,我会在文章中注明您的名字!

历史

目前还没有。

© . All rights reserved.