VBScript如何格式化日期?

Coc*_*Dev 22 vbscript date

我希望日期看起来像MM-DD-YYYY而不是MM/DD/YYYY.

sti*_*net 38

0 = vbGeneralDate - Default. Returns date: mm/dd/yy and time if specified: hh:mm:ss PM/AM.
1 = vbLongDate - Returns date: weekday, monthname, year
2 = vbShortDate - Returns date: mm/dd/yy
3 = vbLongTime - Returns time: hh:mm:ss PM/AM
4 = vbShortTime - Return time: hh:mm


d=CDate("2010-02-16 13:45")
document.write(FormatDateTime(d) & "<br />")
document.write(FormatDateTime(d,1) & "<br />")
document.write(FormatDateTime(d,2) & "<br />")
document.write(FormatDateTime(d,3) & "<br />")
document.write(FormatDateTime(d,4) & "<br />")
Run Code Online (Sandbox Code Playgroud)

如果要使用其他格式,则必须创建自己的函数并解析月,年,日等,并以您的首选格式将它们组合在一起.

Function myDateFormat(myDate)
    d = WhatEver(Day(myDate))
    m = WhatEver(Month(myDate))    
    y = Year(myDate)
    myDateFormat= m & "-" & d & "-" & y
End Function

Function WhatEver(num)
    If(Len(num)=1) Then
        WhatEver="0"&num
    Else
        WhatEver=num
    End If
End Function
Run Code Online (Sandbox Code Playgroud)

编辑:添加函数以格式化日期和月份,就0n好像值小于10.

  • `Right(“00” &amp; Day(myDate), 2)` 已经做了很多工作。 (4认同)

Sam*_*Sam 20

建议在函数中只调用一次"Now",以防止在执行函数期间改变分钟,甚至是白天.

从而:

Function timeStamp()
    Dim t 
    t = Now
    timeStamp = Year(t) & "-" & _
    Right("0" & Month(t),2)  & "-" & _
    Right("0" & Day(t),2)  & "_" & _  
    Right("0" & Hour(t),2) & _
    Right("0" & Minute(t),2) '    '& _    Right("0" & Second(t),2) 
End Function
Run Code Online (Sandbox Code Playgroud)


MBu*_*MBu 9

FormatDateTime的输出取决于"控制面板"中"区域设置"中的配置.因此在其他国家,FormatDateTime(d,2)可以例如返回yyyy-MM-dd.

如果您希望输出为"文化不变",请使用stian.net的解决方案.如果你只是不喜欢日期中的斜杠而你不关心其他国家的日期格式,你可以使用

Replace(FormatDateTime(d,2),"/","-")
Run Code Online (Sandbox Code Playgroud)


小智 6

'对于我使用的唯一文件名

Dim ts, logfile, thisScript

thisScript = LEFT(Wscript.ScriptName,LEN(Wscript.ScriptName)-4) ' assuming .vbs extension

ts = timeStamp
logfile = thisScript & "_" & ts

' ======
Function timeStamp() 
    timeStamp = Year(Now) & "-" & _
    Right("0" & Month(Now),2)  & "-" & _
    Right("0" & Day(Now),2)  & "_" & _  
    Right("0" & Hour(Now),2) & _
    Right("0" & Minute(Now),2) '    '& _    Right("0" & Second(Now),2) 
End Function
' ======
Run Code Online (Sandbox Code Playgroud)