date format in VBS

后端 未结 2 735
感情败类
感情败类 2020-12-06 23:26

I want to get a date in full format in my vbscript. For example, I put
DateParam = FormatDateTime(Date()-1, 2)

But it returns

3/8/201

相关标签:
2条回答
  • 2020-12-07 00:03

    The FormatDateTime function is useless, because it depends on the user specific and global Regional Settings.

    The best (most gain for least effort) solution - tapping into .NET - is flawed for dates; again because of the dependency on the Regional Settings.

    If you want/need to roll your own function, start with something like fmtDate().

    Dim g_oSB : Set g_oSB = CreateObject("System.Text.StringBuilder")
    
    Function sprintf(sFmt, aData)
       g_oSB.AppendFormat_4 sFmt, (aData)
       sprintf = g_oSB.ToString()
       g_oSB.Length = 0
    End Function
    
    Function fmtDate(dtX)
      fmtDate = Join(Array(           _
           Right(100 + Month(dtX), 2) _
         , Right(100 +   Day(dtX), 2) _
         ,              Year(dtX)     _
      ), "/")
    End Function
    
    Dim dtYesterday : dtYesterday = Date() - 1
    WScript.Echo "Yesterday:", dtYesterday, GetLocale()
    WScript.Echo "sprintf (silly)  =>", sprintf("{0:MM/dd/yyyy}", Array(dtYesterday))
    WScript.Echo "sprintf (clumsy) =>", sprintf("{0:MM}/{0:dd}/{0:yyyy}", Array(dtYesterday))
    WScript.Echo "fmtDate          =>", fmtDate(dtYesterday)
    

    output:

    Yesterday: 08.03.2012 1033
    sprintf (silly)  => 03.08.2012
    sprintf (clumsy) => 03/08/2012
    fmtDate          => 03/08/2012
    

    On second thought:

    Escaping the "/" helps to make sprintf() usable:

    WScript.Echo "sprintf (silly me)  =>", sprintf("{0:MM\/dd\/yyyy}", Array(dtYesterday))
    

    output:

    sprintf (silly me)  => 03/08/2012
    

    So don't bother with fmt* functions but use .NET formatting.

    0 讨论(0)
  • 2020-12-07 00:15
    ThisDate = Date()
    
    MyDate = Right("0" & CStr(Month(ThisDate)), 2) & "/" & _
             Right("0" & CStr(Day(ThisDate)), 2) & "/" & CStr(Year(ThisDate))
    
    0 讨论(0)
提交回复
热议问题