简体   繁体   English

如何以TZ格式检索系统时区.net c#

[英]How to retrieve the system timezone in TZ format .net c#

I'm trying to work out how to retrieve the current system timezone in a ( TZ ) format on windows, ie. 我正在尝试研究如何在Windows上以( TZ )格式检索当前系统时区,即。 America/New_York, I need to supply this to an API this application communicates with. America / New_York,我需要将此提供给此应用程序与之通信的API。

I'm currently using 我正在使用

TimeZone.CurrentTimeZone

Which gives me this output 这给了我这个输出

GMT Standard Time

What I hope to get is something like 我希望得到的是类似的东西

Europe/London

Am I missing something simple or is this not available and thus does that mean I need to do the conversion myself? 我错过了一些简单的东西,或者这是不可用的,因此这是否意味着我需要自己进行转换?

I recommend to use NodaTime for that. 我建议使用NodaTime

You can get the timezone of your system like that : 您可以像这样获得系统的时区:

DateTimeZone tz = DateTimeZoneProviders.Tzdb.GetSystemDefault();

It will get the IANA Timezone as you need if you use tz.ToString() 如果您使用tz.ToString() ,它将根据您的需要获得IANA时区

(and apart from that, it is a very nice open source library that handles timezone, datetimes, instants and calendars in a IMHO much more structured and reliable way than the builtin .NET DateTime classes). (除此之外,它是一个非常好的开源库,可以处理IMHO中的时区,日期时间,瞬间和日历,比内置的.NET DateTime类更加结构化和可靠。)

NodaTime is maintained and well supported by some high rep users here in SO ;) . NodaTime得到了SO的一些高代表用户的维护和良好支持;)。


For information, the output that you are getting and you don't want, the one used by .NET, is called BCL Timezone, but you want the IANA Timezone (or TZDB) (which is more accurate) 有关信息,您获得并且不需要的输出(.NET使用的输出)称为BCL时区,但您需要IANA时区(或TZDB)(更准确)

Noda Time is an excellent option. Noda Time是一个很好的选择。 It is a much better and more comprehensive API for working with dates, times, and time zones than what comes built-in to .NET. 与.NET内置的内容相比,它是一个更好,更全面的API,用于处理日期,时间和时区。

However, if getting the system time zone in IANA TZDB format is the only thing you are doing in this space, you may find it simpler to use my TimeZoneConverter library. 但是,如果以IANA TZDB格式获取系统时区是您在此空间中唯一做的事情,您可能会发现使用我的TimeZoneConverter库更加简单。

string tz = TZConvert.WindowsToIana(TimeZoneInfo.Local.Id);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM