为什么SetSystemTime()在Afternoons中表现不同?

时间:2018-06-07 08:36:36

标签: c# winapi windows-10

我编写了以下课程来更改系统日期时间,但我无法理解为什么它在当天的不同时间有不同的功能:

  • 上午:传递给SetTime()的确切时间设置为系统时间。
  • 下午:传递给SetTime() + 1Hr的时间被设置为系统时间,另外一小时来自哪里?

public class SystemDateTimeController
{        

[DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
private extern static bool Win32SetSystemTime(ref SYSTEMTIME sysTime);       


    private struct SYSTEMTIME
    {
        public ushort wYear;
        public ushort wMonth;
        public ushort wDayOfWeek;
        public ushort wDay;
        public ushort wHour;
        public ushort wMinute;
        public ushort wSecond;
        public ushort wMilliseconds;
    }

    public static void SetTime(DateTime NewDateTime)
    {
        try
        {
            SYSTEMTIME systime = new SYSTEMTIME();

            systime.wMilliseconds = (ushort)NewDateTime.Millisecond;
            systime.wSecond = (ushort)NewDateTime.Second;
            systime.wMinute = (ushort)NewDateTime.Minute;
            systime.wHour = (ushort)NewDateTime.Hour;

            systime.wDayOfWeek = (ushort)NewDateTime.DayOfWeek;

            systime.wDay = (ushort)NewDateTime.Day;
            systime.wMonth = (ushort)NewDateTime.Month;
            systime.wYear = (ushort)NewDateTime.Year;

            Win32SetSystemTime(ref systime);
        }
        catch (Exception e)
        {
            Log("Failed to set system date time to: " + NewDateTime.ToString() + ". Exception: " + e.ToString());
        }

    }

}

我知道传递给SetTime()的确切时间以及测试purpouses并消除了对源代码的任何可能性我甚至传递了一个硬编码字符串:Convert.ToDateTime("07/06/2018 13:00:00");

1 个答案:

答案 0 :(得分:1)

SetSystemTime需要UTC。 OP正在向当地时间供电,这就是问题(感谢@IInspectable

为了您的目的,更好地使用SetLocalTime 它始终使用您当地的时区。

问候