获取另一个时区的日期时间,无论当地时区

Dav*_*ave 44 c# datetime .net-2.0

无论用户的本地时区设置为什么,使用C#(.NET 2.0)我都需要确定东部时区的时间(DateTime对象).

我知道这些方法,但似乎没有一种明显的方法来获取不同于用户所在时区的DateTime对象.

 DateTime.Now
 DateTime.UtcNow
 TimeZone.CurrentTimeZone
Run Code Online (Sandbox Code Playgroud)

当然,解决方案需要节省时间.

Mar*_*ell 88

在.NET 3.5中,有TimeZoneInfo一个在这个领域提供了很多功能; 2.0SP1有DateTimeOffset,但这是有限的.

获取UtcNow和添加固定偏移量是作业的一部分,但不支持DST.

所以在3.5中我认为你可以这样做:

DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(
    DateTime.UtcNow, "Eastern Standard Time");
Run Code Online (Sandbox Code Playgroud)

但这在2.0中根本不存在; 抱歉.

  • 即使他不在OP的限制范围内,他回答了我的问题,所以我对此进行了修改:) (3认同)
  • 谢谢!我只想添加:`ReadOnlyCollection <TimeZoneInfo> tz = TimeZoneInfo.GetSystemTimeZones(); DateTime east = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(DateTime.UtcNow,tz [0] .Id);` (3认同)

And*_*ndy 8

正如其他人提到的,.NET 2不包含任何时区信息.但是,信息存储在注册表中,并且围绕它编写包装类非常简单:

SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones
Run Code Online (Sandbox Code Playgroud)

包含所有时区的子键.TZI字段值包含时区的所有转换和偏置属性,但它们都填充在二进制数组中.最重要的位(偏差和日光)分别是存储在0和8位的int32:

int bias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 0);
int daylightBias = BitConverter.ToInt32((byte[])tzKey.GetValue("TZI"), 8);
Run Code Online (Sandbox Code Playgroud)

这是如何从注册表获取时区信息(DST)的存档


Chr*_*rds 6

来自 - http://msdn.microsoft.com/en-us/library/system.timezoneinfo.converttimefromutc.aspx

这允许按名称找到时区,以防美国从伦敦子午线向西或向东漂浮15度.

DateTime timeUtc = DateTime.UtcNow;
try
{
   TimeZoneInfo cstZone = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
   DateTime cstTime = TimeZoneInfo.ConvertTimeFromUtc(timeUtc, cstZone);
   Console.WriteLine("The date and time are {0} {1}.", 
                     cstTime, 
                     cstZone.IsDaylightSavingTime(cstTime) ?
                             cstZone.DaylightName : cstZone.StandardName);
}
catch (TimeZoneNotFoundException)
{
   Console.WriteLine("The registry does not define the Central Standard Time zone.");
}                           
catch (InvalidTimeZoneException)
{
   Console.WriteLine("Registry data on the Central STandard Time zone has been corrupted.");
}
Run Code Online (Sandbox Code Playgroud)