[date] VBScript How can I Format Date?

I want the date to look like MM-DD-YYYY instead of MM/DD/YYYY.

This question is related to date vbscript

The answer is


This snippet also solve this question with datePart function. I've also used the right() trick to perform a rpad(x,2,"0").

option explicit

Wscript.Echo "Today is " & myDate(now)

' date formatted as your request
Function myDate(dt)
    dim d,m,y, sep
    sep = "-"
    ' right(..) here works as rpad(x,2,"0")
    d = right("0" & datePart("d",dt),2)
    m = right("0" & datePart("m",dt),2)
    y = datePart("yyyy",dt)
    myDate= m & sep & d & sep & y
End Function

The output of FormatDateTime depends on configuration in Regional Settings in Control Panel. So in other countries FormatDateTime(d, 2) may for example return yyyy-MM-dd.

If you want your output to be "culture invariant", use myDateFormat() from stian.net's solution. If you just don't like slashes in dates and you don't care about date format in other countries, you can just use

Replace(FormatDateTime(d,2),"/","-")

'for unique file names I use

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
' ======

For anyone who might still need this in the future. My answer is very similar to qaweb, just a lot less intimidating. There seems to be no cool automatic simple function to formate date in VBS. So you'll have to do it manually. I took the different components of the date and concatenated them together.

Dim timeStamp
timeStamp = Month(Date)&"-"&Day(Date)&"-"&Year(Date)
run = msgbox(timeStamp)

Which will result in 11-22-2019 (depending on the current date)


Suggest calling 'Now' only once in the function to guard against the minute, or even the day, changing during the execution of the function.

Thus:

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

Although answer is provided I found simpler solution:

Date:

01/20/2017

By doing replace

CurrentDate = replace(date, "/", "-")

It will output:

01-20-2017