如何设置系统时间?

肯定是要借助API了,那么具体该怎么做呢?通过搜索,在网上转载的比较多的一篇文章:《API 设置调整系统当前时间》,不知道首发在哪里,如果有知道的告诉我一下。

这篇文章,提到得解决办法是调用API函数SetSysTime。其中SetTime(NewTime As String)方法有个小错误

Public Sub SetTime(NewTime As String)
' 功能: 设置系统时间
   Dim lpSystemTime As SYSTEMTIME               '时间信息
   Dim ZoneNum As Integer
    ZoneNum = getZoneNum()
    With lpSystemTime
        .wYear = Year(NewTime)
        .wMonth = Month(NewTime) + 1 '这个地方有问题,应该不用加1
        .wDayOfWeek = -1
        .wDay = Day(NewTime)
        .wHour = Hour(NewTime) + ZoneNum
        .wMinute = Minute(NewTime)
        .wSecond = Second(NewTime)
        .wMilliseconds = 0
    End With
   SetSystemTime lpSystemTime
End Sub

另外大家看设置小时的代码 .wHour = Hour(NewTime) + ZoneNum,可能会觉得比较奇怪,为什么要加ZoneNum呢?大家一定还记得因为地球自转的原因,地球上不同地方的时间是不一样的,一共分成24个时区,我们国家处在东八区。而SetSystemTime()默认设置的为UTC时间,当系统设置时间的时候还会按照时区加上一个偏差。而我们的用的北京时间也就是东八区时间,刚好比UTC多了8个小时,ZoneNum就是通过计算得到的时区差。其实为了设置为本地系统时间,可以利用另一个API函数SetLocalTIme(),就不用考虑时区差问题。

Public Declare Function SetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME) As Long
Public Declare Function GetTimeZoneInformation Lib "kernel32" (lpTimeZoneInformation As TIME_ZONE_INFORMATION) As Long
Public Type SYSTEMTIME
    wYear As Integer
    wMonth As Integer
    wDayOfWeek As Integer
    wDay As Integer
    wHour As Integer
    wMinute As Integer
    wSecond As Integer
    wMilliseconds As Integer
End Type

Public Sub SetTime(NewTime As String)
' 功能: 设置系统时间
   Dim lpSystemTime As SYSTEMTIME               '时间信息
   Dim ZoneNum As Integer
    With lpSystemTime
        .wYear = Year(NewTime)
        .wMonth = Month(NewTime)
        .wDayOfWeek = -1
        .wDay = Day(NewTime)
        .wHour = Hour(NewTime)
        .wMinute = Minute(NewTime)
        .wSecond = Second(NewTime)
        .wMilliseconds = 0
    End With
   SetLocalTime lpSystemTime
End Sub

'调用

Private Sub Command1_Click()
    On Error Resume Next
   Call SetTime("2007-12-10 17:30:10")
End Sub
本文来源于网络小筑 http://www.iwebtrados.com.cn/ , 原文地址:http://www.iwebtrados.com.cn/post/277.html