简体   繁体   中英

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. America/New_York, I need to supply this to an API this application communicates with.

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.

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

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

NodaTime is maintained and well supported by some high rep users here in 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)

Noda Time is an excellent option. It is a much better and more comprehensive API for working with dates, times, and time zones than what comes built-in to .NET.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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