SetSystemTime kernel32中的奇怪行为

时间:2014-08-07 09:10:03

标签: .net vb.net windows kernel32

我有以下代码:

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

可能导致此行为的原因。时区设置为伦敦,我们目前正在夏令时直到十月。操作系统是Win7 Embedded Standard。

有什么想法吗?

1 个答案:

答案 0 :(得分:1)

请改用SetLocalTime功能,请仔细记录其文档中的注释:

  

系统内部使用UTC。因此,当您调用SetLocalTime时,系统将使用当前时区信息执行转换,包括夏令时设置。请注意,系统使用当前时间的夏令时设置,而不是您设置的新时间。因此,为了确保正确的结果,请再次调用SetLocalTime,现在第一次调用已更新夏令时设置。