有没有人在 VBScript 中有一种简单的方法来获取 UTC 的当前时间?
谢谢,克里斯
我使用一个简单的技术
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate (now())
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & dateTime.GetVarDate (false)
如果您想将 UTC 转换回本地时间,请执行以下操作:
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate now(),false REM Where now is the UTC date
wscript.echo cdate(dateTime.GetVarDate (true))
那里有很多例子。如果您可以访问注册表,则此注册表对您有用:
od = now()
set oShell = CreateObject("WScript.Shell")
atb = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" &_
"Control\TimeZoneInformation\ActiveTimeBias"
offsetMin = oShell.RegRead(atb)
nd = dateadd("n", offsetMin, od)
Response.Write("Current = " & od & "<br>UTC = " & nd)
您可以从Win32_TimeZone WMI
类中获得时间偏差。
myDate = "9/4/2013 17:23:08"
For Each objItem In GetObject(_
"winmgmts:\\.\root\cimv2").ExecQuery(_
"Select * from Win32_TimeZone")
bias = objItem.Bias
Next
myDate = DateAdd("n", bias, myDate)
WScript.Echo myDate
这是一个将日期格式化为 UTC 的示例。请注意,您不能使用它格式化到毫秒级别。
Dim formattedDate
Dim utcDate
Set objShell = WScript.CreateObject("WScript.Shell")
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate(now())
utcDate = dateTime.GetVarDate(false)
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & utcDate
formattedDate = DatePart("yyyy",utcDate) & "-" & Right("0" & DatePart("m",utcDate), 2) & "-" & Right("0" & DatePart("d",utcDate), 2)
& "T" & Right("0" & DatePart("h",utcDate), 2) & ":" & Right("0" & DatePart("n",utcDate), 2)
& ":" & Right("0" & DatePart("s",utcDate), 2) & ".000+0000"
wscript.echo formattedDate
'results in a format that looks like this: 1970-01-01T00:00:00.000+0000
set dateTime=Nothing
set objShell=Nothing
基于上述函数 - 返回要添加到当前时间以返回 UTC 的增量值。
或者使用 DATE+TIME 调用它以返回 UTC。
调用一次并存储在全局变量中以将任何日期/时间偏移到 UTC。相反,从任何 UTC 中减去它以获取当前时区的时间。
底部的额外 ROUND 是为了补偿转换到最接近秒的浮点错误。
Function Time_add_To_get_UTC(Optional DateTime = 0) ''as double
'' Returns value to add to current time to get to UTC
''Based on above functions : )
''return offset from current time to UTC
''https://stackoverflow.com/questions/15887700/utc-time-assignment-in-vbscript/22842128
Dim SWDT ''As SWbemDateTime
Dim dt ''As Date
Set SWDT = CreateObject("WbemScripting.SWbemDateTime")
dt = Date + Time()
SWDT.SetVarDate (dt)
Time_add_To_get_UTC = CDbl(SWDT.GetVarDate(False)) - CDbl(SWDT.GetVarDate(True))
Time_add_To_get_UTC = CDbl(Round(Time_add_To_get_UTC * 24 * 60 * 60, 0) / 24 / 60 / 60)
Time_add_To_get_UTC = DateTime + Time_add_To_get_UTC
End Function
使用 SetVarDate 时,由于过渡到夏令时(从 +060 到 +120)而导致的偏移量变化发生得太快了一小时。RegRead(HKLM\..\ActiveTimeBias) 方法很准确。如果需要复制,只需将电脑时钟置于预期转换时间之前和之后的时间并检查结果。