简体   繁体   中英

Is DST enabled?

In Windows 7, Time Zone Settings, you can enable or disable the "Automatically adjust clock for Daylight Saving Time". If this is disabled, then the PC clock will always show standard time, even if the timezone is set to a timezone that follows Daylight Saving Time.

This question asks if DST is enable, but the answer only says if the current date/time is within the DST rules, so it should be adjusted, but the settings for the OS says to keep the time in the standard time zone.

How do I get the "Automatically adjust clock for Daylight Saving Time" from C#

If you just want to know whether DST is supported by the local time zone, use:

bool hasDST = TimeZoneInfo.Local.SupportsDaylightSavingTime;

This will be false in either of these conditions:

  • The selected time zone does not use DST (such as Arizona and Hawaii)

  • The selected time zone uses DST but the user has cleared the "Automatically Adjust Clock for Daylight Saving Time" checkbox.

If you specifically want to know if the user has disabled DST for a time zone that normally supports it, then do this:

bool actuallyHasDST = TimeZoneInfo.Local.SupportsDaylightSavingTime;
bool usuallyHasDST = TimeZoneInfo.FindSystemTimeZoneById(TimeZoneInfo.Local.Id)
                                 .SupportsDaylightSavingTime;
bool dstDisabled = usuallyHasDST && !actuallyHasDST;

The dstDisabled variable will be true only when the user has specifically cleared the "Automatically Adjust Clock for Daylight Saving Time" checkbox. If the box doesn't exist because the zone doesn't support DST to begin with, then dstDisabled will be false.

How does this work?

  • Windows stores the chosen time zone settings in the registry at:

     HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\TimeZoneInformation 
  • The DynamicDaylightTimeDisabled key is set to 1 when the box is cleared. Otherwise it is set to 0 .

    One of the answers in the other question you mentioned specifically checked for this value, which is also an acceptable solution.

  • Calling TimeZoneInfo.Local takes into account all of the information in that key.

  • Looking up the time zone by the Id does not take into account any of the information in the registry, other than the Id itself, which is stored in the TimeZoneKeyName value.

  • By comparing the registry-created information against the looked-up information, you can determine whether DST has been disabled.

Note that this is also well described in the remarks section of the MSDN documentation for TimeZoneInfo.Local .

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