2

システム時刻を変更するこのコードがあります。

このコードは機能しますが、なぜかローカル システムのタイム ゾーンを受け入れません。

それを行うには、さらにいくつかのメソッドを追加する必要があるようですまたは??

どうして?

どんな手掛かり?

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適用することでした。 ただし、正しいタイムゾーンも適用する必要があります。

4

2 に答える 2

2

SetSystemTimeは UTC 時間のみを受け入れます。したがって、必要に応じて、C# コードでローカルから UTC への変換を行う必要があります。

現在のシステムの時刻と日付を設定します。システム時刻は協定世界時 (UTC) で表されます。

于 2012-04-27T18:11:51.223 に答える
1

APIを呼び出す前に、時間を現地時間からUTCに変換する必要があるということですか?

  var utcTime=TimeZone.CurrentTimeZone.ToUniversalTime(new DateTime(){...});  
于 2012-04-27T18:16:26.030 に答える