DateDiff和区域设置

时间:2013-01-07 09:30:47

标签: vbscript datediff regional-settings

我有一个VBscript可以运行在遍布全球的设备上,因此可以使用各种区域设置。

我的脚本的一部分是计算2个日期之间的差异,但我无法使用一致的结果。

一个例子:

'Get system date in EU format    
dEUDate = Right("0" & DatePart("d",Date), 2) & "-" & Right("0" & DatePart("m",Date), 2) & "-" & DatePart("yyyy",Date)

'Read date/time value from an application in registry - will return e.g. 05-01-2013 07-19-00
dateKLAVDef = UCase(objShell.RegRead(strKLAVStateKey & "\Protection_BasesDate"))

'Find date difference
iAVDefAge = DateDiff("d", Left(dateKLAVDef, 10), dEUDate)

WScript.Echo "AV def.: " & dateKLAVDef & vbTab & "Current date: " & dEUDate & vbTab & "Diff: " & iAVDefAge

当设备配置了EU区域设置时,会产生正确的结果:

AV def。:05-01-2013 07-19-00当前日期:07-01-2013差异:2

当设备配置了非欧盟区域设置(例如英语(美国))(从脚本的角度来看)不正确时,这是结果:

AV def。:05-01-2013 07-19-00当前日期:07-01-2013差异:61

如何使用非欧盟区域设置?

提前致谢。

1 个答案:

答案 0 :(得分:1)

似乎dateKLAVDef总是在dd-MM-yyyy hh-mm-ss中。那是对的吗?然后,您必须从此字符串中检索日期,月份和年份,并使其为Date DateSerial(y, m, d)。它将自动转换为正确的区域设置格式。用当前日期做一个DateDiff等等,你准备好了:

' Read date/time value from an application in registry - will 
' return e.g. 05-01-2013 07-19-00
dateKLAVDef = "05-01-2013 07-19-00"

' Define a pattern for the given string
dateKLAVDefPattern = "^(\d+)-(\d+)-(\d+) .*"

' Make a regular expression
Set re = new RegExp
re.Pattern = dateKLAVDefPattern

' Execute the regex
Set matches = re.Execute(dateKLAVDef)

' Retrieve the submatches from the match
dateKLAVDefDay = matches(0).submatches(0)
dateKLAVDefMonth = matches(0).submatches(1)
dateKLAVDefYear = matches(0).submatches(2)

' recreate the dateKLAVDef date as a real date object
dateKLAVDefAsDate = DateSerial(dateKLAVDefYear, dateKLAVDefMonth, dateKLAVDefDay)

' Do a datediff on the created date and the current date
iAVDefAge = DateDiff("d", dateKLAVDefAsDate, Date())
MsgBox iAVDefAge