C# 无论本地时区如何,获取另一个时区的日期时间

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/441109/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-04 03:29:03  来源:igfitidea点击:

Get DateTime For Another Time Zone Regardless of Local Time Zone

c#datetime.net-2.0

提问by Dave

Regardless of what the user's local time zone is set to, using C# (.NET 2.0) I need to determine the time (DateTime object) in the Eastern time zone.

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

I know about these methods but there doesn't seem to be an obvious way to get a DateTime object for a different time zone than what the user is in.

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

 DateTime.Now
 DateTime.UtcNow
 TimeZone.CurrentTimeZone

Of course, the solution needs to be daylight savings time aware.

当然,解决方案需要注意夏令时。

采纳答案by Andy

As everyone else mentioned, .NET 2 doesn't contain any time zone information. The information is stored in the registry, though, and its fairly trivial to write a wrapper class around it:

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

SOFTWARE\Microsoft\Windows NT\CurrentVersion\Time Zones

contains sub-keys for all time zones. The TZI field value contains all the transition and bias properties for a time zone, but it's all stuffed in a binary array. The most important bits (bias and daylight), are int32s stored at positions 0 and 8 respectively:

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

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

Here's an archive of How to get time zone info (DST) from registry?

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

回答by Charles Bretana

How about

怎么样

 DateTime lclTime = DateTime.Now;
 DateTime ept = lclTime.ToUniversalTime().AddHours(
                   IsEasternDaylightSavingTime(
                       lclTime.ToUniversalTime())? -5: -4)

or if you already have local UTC, just

或者如果您已经拥有本地 UTC,只需

 DateTime lclUtc = DateTime.UtcNow;
 DateTime ept = lclUtc.AddHours(
                  IsEasternDaylightSavingTime(lclUtc)? -5: -4)

Use static dictionary of hard coded values for Spring-forward and fall back dates for Eastern time for the next 50 years.. That's only 300 bytes or so... and then index into that to determine whether it's Daylight savings time on east coast... As pointed out, you don;t care whether it's dST in local zone or not...

使用硬编码值的静态字典作为未来 50 年东部时间的 Spring-forward 和回退日期。那只有 300 个字节左右......然后索引到它以确定它是否是东海岸的夏令时。 .. 正如所指出的,你不在乎它是否是本地区域的 dST ......

 private static bool IsEasternDaylightSavingTime(DateTime utcDateTime)
   {
        // hard coded method to determine 
        // whether utc datetime is Eastern Standard time
        // or Eastern Daylight Time
   }

回答by Marc Gravell

In .NET 3.5, there is TimeZoneInfo, which provides a lot of functionality in this area; 2.0SP1 has DateTimeOffset, but this is much more limited.

在 .NET 3.5 中,有TimeZoneInfo,它在这方面提供了很多功能;2.0SP1 有DateTimeOffset,但这更加有限。

Getting UtcNowand adding a fixed offset is part of the job, but isn't DST-aware.

获取UtcNow和添加固定偏移量是工作的一部分,但不是 DST 感知的。

So in 3.5 I think you can do something like:

因此,在 3.5 中,我认为您可以执行以下操作:

DateTime eastern = TimeZoneInfo.ConvertTimeBySystemTimeZoneId(
    DateTime.UtcNow, "Eastern Standard Time");

But this simply doesn't exist in 2.0; sorry.

但这在 2.0 中根本不存在;对不起。

回答by Christopher Edwards

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

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

This allows a time zone to be found by name, in case the US ever floats 15 degrees west or east from the London meridian.

这允许按名称找到时区,以防美国从伦敦子午线向西或向东浮动 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.");
}

回答by Robert C. Barth

I'll save you the time and tell you that there is no way in .net proper, version 2.0 to get a DateTime object for another time zone different from the one that the software is running on (other than UTC).

我会为您节省时间并告诉您,在 .net 版本 2.0 中无法获取另一个时区的 DateTime 对象,该对象与运行软件的时区不同(UTC 除外)。

However, that doesn't mean there isn't a way to do it outside of .net. Take a look hereat the TimeZoneInformation class. This class wraps some p/invoke stuff to the Win O/S to get the time zone information from the O/S. I successfully used it back when 2.0 was new and it worked very well. The site I was working on had to be able to show every date/time local to the user and had to be DST-aware, and this class filled the bill for us.

然而,这并不意味着在 .net 之外没有办法做到这一点。看看这里的TimeZoneInformation类。此类将一些 p/invoke 内容包装到 Win O/S 以从 O/S 获取时区信息。当 2.0 是新版本时,我成功地使用了它,并且效果很好。我正在开发的站点必须能够向用户显示本地的每个日期/时间,并且必须具有 DST 感知能力,而这个类为我们填写了账单。

回答by Jay

A date comparison is a date comparison. DateTime just wraps a memory structure which is defined in ticks and makes methods to access commonly used parts of the memory e.g. day or year or Time or TimeOfDay etc.

日期比较是日期比较。DateTime 只是包装了一个在刻度中定义的内存结构,并创建方法来访问内存的常用部分,例如日或年或时间或 TimeOfDay 等。

Furthermore conversion is only possible if you know both the source snd destination offsets and then the calculation is always as given is given by -1 * (sourceOffset - destOffset)

此外,只有当您知道源 snd 目标偏移量并且计算始终如给定时才可能进行转换,如下所示 -1 * (sourceOffset - destOffset)

Where the part in parenthesis represents the time zone difference.

其中括号中的部分表示时区差异。

Please also see

另请参阅

Get eastern time in c# without converting local time

在 C# 中获取东部时间而不转换当地时间