Detect if the DST is currently enabled

放肆的年华 提交于 2019-12-22 09:12:17

问题


I need to find an easy way to know if the local machine's 'automatically adjust clock for Daylight Saving Time' option is enabled. If the option's on, I need to know whether it is currently applied (i.e. is it DST currently in the system). Thanks in advance


回答1:


You can find the current system default time zone and whether it is currently using DST (Daylight Saving Time) like this (.NET 3.5 onwards):

TimeZoneInfo zone = TimeZoneInfo.Local;
if (zone.SupportsDaylightSavingTime)
{
    Console.WriteLine("System default zone uses DST...");
    Console.WriteLine("In DST? {0}", zone.IsDaylightSavingTime(DateTime.UtcNow));       
}
else
{
    Console.WriteLine("System default zone does not use DST.");
}



回答2:


Another option may be is DateTime.IsDaylightSavingTime method. Check MSDN.

if (DateTime.Now.IsDaylightSavingTime())
    Console.WriteLine("Daylight Saving");
else
    Console.WriteLine("No Daylight Saving");



回答3:


You can read the registry to determine if the checkbox is checked or not. Read this key,

HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation DynamicDaylightTimeDisabled

= 0 or 1 (disabled)

So something like :

    Dim retval As Object = Microsoft.Win32.Registry.GetValue("HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation", "DynamicDaylightTimeDisabled", 0)
    If retval IsNot Nothing Then
        Select Case CInt(retval)
            Case 0
                Trace.WriteLine("Automatically adjust clock for Daylight Saving Time is checked")
            Case 1
                Trace.WriteLine("Automatically adjust clock for Daylight Saving Time is NOT checked")
        End Select
    End If



回答4:


Here is another example in C#

private static bool IsDayLightSavingsEnabled()
{
  try
  {
    var result = Registry.GetValue(@"HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\TimeZoneInformation", "DynamicDaylightTimeDisabled", 1);
    return !Convert.ToBoolean(result); //0 - Checked/enabled,  1 - Unchecked/disabled
  }
  catch
  { }
  return false;
}


来源:https://stackoverflow.com/questions/9937947/detect-if-the-dst-is-currently-enabled

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!