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

发布于 2024-07-11 13:53:02 字数 227 浏览 5 评论 0原文

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

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

 DateTime.Now
 DateTime.UtcNow
 TimeZone.CurrentTimeZone

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

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.

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.Now
 DateTime.UtcNow
 TimeZone.CurrentTimeZone

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

三生殊途 2024-07-18 13:53:03

在.NET 3.5中,有 TimeZoneInfo,提供了很多这方面的功能; 2.0SP1 有 DateTimeOffset,但是这是非常有限的。

获取 UtcNow 并添加固定偏移量是工作的一部分,但不支持 DST。

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

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

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

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.

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

So in 3.5 I think you can do something like:

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

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

因为看清所以看轻 2024-07-18 13:53:03

来自 - 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.");
}

From - 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.

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.");
}
晌融 2024-07-18 13:53:03

正如其他人提到的,.NET 2 不包含任何时区信息。
不过,这些信息存储在注册表中,围绕它编写一个包装类相当简单:

SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones

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

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

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

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:

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:

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?

鸠书 2024-07-18 13:53:03

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

然而,这并不意味着没有办法在.net 之外做到这一点。 请查看此处的 TimeZoneInformation 类。 此类将一些 p/invoke 内容包装到 Win O/S,以从 O/S 获取时区信息。 我在2.0刚推出的时候就成功使用过它,效果非常好。 我正在开发的网站必须能够显示用户本地的每个日期/时间,并且必须能够感知 DST,而这个类满足了我们的要求。

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).

However, that doesn't mean there isn't a way to do it outside of .net. Take a look here at 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.

兔小萌 2024-07-18 13:53:03

或者

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

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

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

使用硬编码值的静态字典作为未来 50 年东部时间的春季向前和向后日期。这只有 300 字节左右......然后索引到该字典确定东海岸是否是夏令时...正如所指出的,您不关心当地是否是夏令时...

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

How about

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

or if you already have local UTC, just

 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...

 private static bool IsEasternDaylightSavingTime(DateTime utcDateTime)
   {
        // hard coded method to determine 
        // whether utc datetime is Eastern Standard time
        // or Eastern Daylight Time
   }
聊慰 2024-07-18 13:53:03

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

此外,只有当您知道源和目标偏移量以及计算时,才可以进行转换总是由 -1 * (sourceOffset - destOffset) 给出,

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

另请参阅

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

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.

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)

Where the part in parenthesis represents the time zone difference.

Please also see

Get eastern time in c# without converting local time

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文