【问题标题】:Changing system time doesn't accept Time Zone更改系统时间不接受时区
【发布时间】:2012-04-27 18:04:25
【问题描述】:

我有这个代码来改变系统时间。

此代码有效,但不知何故不接受本地系统时区。

看来我必须添加更多方法才能做到这一点??

怎么可能???

有什么线索吗?

public static class SystemFunctions
    {
        public struct SystemTime
        {
            public ushort Year;
            public ushort Month;
            public ushort DayOfWeek;
            public ushort Day;
            public ushort Hour;
            public ushort Minute;
            public ushort Second;
            public ushort Millisecond;
        };

        [DllImport("kernel32.dll", EntryPoint = "GetSystemTime", SetLastError = true)]
        public extern static void Win32GetSystemTime(ref SystemTime sysTime);

        [DllImport("kernel32.dll", EntryPoint = "SetSystemTime", SetLastError = true)]
        [return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
        public extern static bool Win32SetSystemTime(ref SystemTime sysTime);

        public static bool SetSystemTime(DateTime dateTime)
        {
            SystemTime updatedTime = new SystemTime();
            updatedTime.Year = (ushort)dateTime.Year;
            updatedTime.Month = (ushort)dateTime.Month;
            updatedTime.Day = (ushort)dateTime.Day;
            // UTC time; it will be modified according to the regional settings of the target computer so the actual hour might differ
            updatedTime.Hour = (ushort)dateTime.Hour;
            updatedTime.Minute = (ushort)dateTime.Minute;
            updatedTime.Second = (ushort)dateTime.Second;
            // Call the unmanaged function that sets the new date and time instantly
            return Win32SetSystemTime(ref updatedTime);
        }
    }

更新

所以最终的解决方案是将本地时间转换为ToUniversalTime 并应用它。 但在我们还必须应用正确的时区之前。

【问题讨论】:

标签: c# .net winapi interop


【解决方案1】:

SetSystemTime 仅接受 UTC 时间。因此,如果需要,您需要在 C# 代码中将本地转换为 UTC。

设置当前系统时间和日期。系统时间以协调世界时 (UTC) 表示。

【讨论】:

【解决方案2】:

您的意思是在调用api之前需要将时间从本地时间转换为UTC?

  var utcTime=TimeZone.CurrentTimeZone.ToUniversalTime(new DateTime(){...});  

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多