文章摘要
这篇文章介绍了名为 `Date2ISO.vbs` 的VBA脚本,用于将给定的日期和/或时间转换为ISO格式。脚本的主要功能包括:
1. **处理命令行参数**:
- 如果没有参数,则使用当前日期和时间。
- 如果有参数,则将第一个参数作为日期,第二个参数(如果存在)作为时间。
2. **日期和时间转换**:
- 使用 `CDate` 函数将输入的字符串转换为 `Date` 类型。
- 根据参数选项 `/D` 或 `/T`,只返回日期或时间。
3. **错误处理**:
- 如果输入的参数数量超过预期或格式不正确,脚本会提示错误。
4. **日期和时间格式化**:
- 使用 `DatePartLZ` 函数提取年、月、日、小时、分钟和秒,并在必要时添加前导零以确保格式正确。
脚本还附带了帮助文档,详细解释了参数和选项的使用方法。
Option Explicit
Dim blnDate, blnTime
Dim dtmDate
Dim intDay, intFormat, intHour, intMin, intMonth, intSec, intUTC, intValid, intYear
Dim strISO
With WScript.Arguments
‘ Check command line arguments
If .Unnamed.Count=0 Then dtmDate=Now
If .Unnamed.Count > 0 Then dtmDate=.Unnamed(0)
If .Unnamed.Count > 1 Then dtmDate=dtmDate & ” ” & .Unnamed(1)
If .Unnamed.Count > 2 Then dtmDate=dtmDate & ” ” & .Unnamed(2)
If .Unnamed.Count > 3 Then Syntax
On Error Resume Next
dtmDate=CDate( dtmDate )
If Err Then
On Error Goto 0
Syntax
End If
On Error Goto 0
If Not IsDate( dtmDate ) Then Syntax
intValid=0
blnDate=True
blnTime=True
If .Named.Exists( “D” ) Then
blnDate=True
blnTime=False
intValid=intValid + 1
End If
If .Named.Exists( “T” ) Then
blnDate=False
blnTime=True
intValid=intValid + 1
End If
If intValid <> .Named.Count Then Syntax
If intValid > 1 Then Syntax
End With
‘ Format the output string
intYear=DatePartLZ( “yyyy”, dtmDate )
intMonth=DatePartLZ( “m”, dtmDate )
intDay=DatePartLZ( “d”, dtmDate )
intHour=DatePartLZ( “h”, dtmDate )
intMin=DatePartLZ( “n”, dtmDate )
intSec=DatePartLZ( “s”, dtmDate )
If blnDate Then strISO=intYear & “-” & intMonth & “-” & intDay
If blnTime Then strISO=strISO & ” ” & intHour & “:” & intMin & “:” & intSec
‘ Display the result
WScript.Echo Trim( strISO )
Function DatePartLZ( myInterval, myDate )
‘ Add a leading zero to the DatePart() if necessary
Dim strDatePart
strDatePart=DatePart( myInterval, myDate )
If Len( strDatePart ) < 2 Then strDatePart=”0″ & strDatePart
DatePartLZ=strDatePart
End Function
Sub Syntax
WScript.Echo vbcrlf _
& “Date2ISO.vbs, Version 1.02” _
& vbCrLf _
& “Convert any date/time to ISO date/time” _
& vbCrLf & vbCrLf _
& “Usage: CSCRIPT.EXE //NoLogo Date2ISO.vbs date [ time ] [ /D | /T ]” _
& vbCrLf & vbCrLf _
& “Where: “”date”” is the date to convert (default: current date/time)” _
& vbCrLf _
& ” “”time”” is the optional time to convert” _
& vbCrLf _
& ” /D return date only (default: both date and time)” _
& vbCrLf _
& ” /T return time only (/D and /T are mutually exclusive)” _
& vbCrLf & vbCrLf _
& “Note: If the specified date is ambiguous, the current user’s date” _
& vbCrLf _
& ” and time format is assumed.” _
& vbCrLf & vbCrLf _
& “Written by Rob van der Woude” _
& vbCrLf _
& “http://www.robvanderwoude.com”
WScript.Quit 1
End Sub