我有以下代码:
Public Class SetSystemTime
Structure SYSTEMTIME
Public wYear As Short
Public wMonth As Short
Public wDayOfWeek As Short
Public wDay As Short
Public wHour As Short
Public wMinute As Short
Public wSecond As Short
Public wMilliseconds As Short
End Structure
Public Declare Function SetSystemTime Lib "kernel32" (ByRef lpSystemTime As SYSTEMTIME) As Boolean
End Class
Private Sub SetDateTime(dt As DateTime)
Dim dateTimeStruct As SetSystemTime.SYSTEMTIME
Dim incHour As Integer = DateDiff(DateInterval.Hour, Now, Date.UtcNow)
With dateTimeStruct
.wDay = dt.Day
.wDayOfWeek = dt.DayOfWeek
.wHour = dt.Hour + incHour
.wMilliseconds = dt.Millisecond
.wMinute = dt.Minute
.wMonth = dt.Month
.wSecond = dt.Second
.wYear = dt.Year
End With
SetSystemTime.SetSystemTime(dateTimeStruct)
End Sub
我看到的行为是,在 2014-08-04 04:15:07,上面的 SetDateTime 方法是用 dt 作为 04/08/2014 04:15:07 执行的,所以有效地设置了时间,但是在现实,没有改变。我的日志显示,由于更改,PC 时钟跳至 2014-08-04 05:15:07。 随后,在2014-08-04 13:00:28(PC时间14:00:28),再次调用该方法,将时钟设置回2014-08-04 13:00:28
什么可能导致此行为。时区设置为伦敦,目前我们在 10 月之前都实行夏令时。操作系统为Win7 Embedded Standard。
有什么想法吗?
最佳答案
使用SetLocalTime函数,请仔细注意其文档中的注释:
The system uses UTC internally. Therefore, when you call SetLocalTime, the system uses the current time zone information to perform the conversion, including the daylight saving time setting. Note that the system uses the daylight saving time setting of the current time, not the new time you are setting. Therefore, to ensure the correct result, call SetLocalTime a second time, now that the first call has updated the daylight saving time setting.
关于.net - SetSystemTime kernel32 中的奇怪行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25178492/