.net - SetSystemTime kernel32 中的奇怪行为

标签 .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

什么可能导致此行为。时区设置为伦敦,目前我们在 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/

相关文章:

C# 在运行时或更早的时候设置进程描述

windows - 使用加载时动态链接指定 "back-up"加载路径?

c# - 从控制台程序记录到 txt 文件的有效方法

.net - 函数内的 jQuery Overlay

.net - 如何使用同一个 SqlConnection 对象在多个 SqlCommand 中声明和使用 T-SQL 变量来执行多次插入?

vb.net - 在 VB.Net 中将位写入二进制文件

sql - 涉及成员时的简单 select 语句

c# - 事件未在表单中正确引发

mysql - 从数据库中选择 bool 字段 = false

windows - Docker native Windows 支持?