【发布时间】:2017-03-22 12:21:54
【问题描述】:
我从我的 c# 应用程序调用了 SetSystemTime。但是,如果我将 Windows 时区设置为与 UTC 的非零偏移量,有时似乎会调整系统时钟,就好像我提供的时间是 UTC(即转换为本地时间),而其他时候则不是,它只是直接将时间设置为date参数。
[StructLayout(LayoutKind.Sequential)]
internal struct SystemTime
{
public short Year;
public short Month;
public short DayOfWeek;
public short Day;
public short Hour;
public short Minute;
public short Second;
public short Milliseconds;
}
[DllImport("kernel32.dll", SetLastError = true)]
internal static extern bool SetSystemTime(ref SystemTime st);
public static bool AdjustSystemClock(DateTime date)
{
SystemTime systemTime = new SystemTime();
systemTime.Year = (short)date.Year;
systemTime.Month = (short)date.Month;
systemTime.Day = (short)date.Day;
systemTime.Hour = (short)date.Hour;
systemTime.Minute = (short)date.Minute;
systemTime.Second = (short)date.Second;
return SetSystemTime(ref systemTime);
}
区别似乎是:当我使用 Windows 设置时区,然后启动应用程序时,当我调用 SetSystemTime() 时,它会调整提供的时间,就好像它是 UTC。
但是当我使用SetDynamicTimeZoneInformation() 函数设置时区时,重新启动应用程序然后调用SetSystemTime() 然后它会直接将时间设置为我提供的时间,而不考虑时区。
这是预期的行为吗?如何使两种设置时区的方法保持一致?
【问题讨论】:
-
SetSystemTime() 几乎从不“将时间直接设置为我提供的时间”。它设置 UTC 时间。除非您居住在 UTC+0 时区的爱尔兰。不完全是祝福。除非计算机位于飞机上,否则随机调用 SetDynamicTimeZoneInformation() 通常是不明智的 :) 使 .NET 程序知道时区更改需要重新启动它(就像您所做的那样)或调用 CultureInfo.ClearCachedData + TimeZoneInfo.ClearCachedData。不要这样做。
-
Windows 计算机自动同步时间。使用内置功能不是更安全吗?您可以更改同步频率或强制同步through settings and the Win32tm tool