Search code examples
stringdatevbscriptformats

VB Script date formats "YYYYMMDDHHMMSS"


As title surgest I need to fomat the now () function to display on the format "YYYYMMDDHHMMSS"

I did have a play about trying to split it out but this drops leading zeros that I need to retain

example below mydt was "27/02/2015 13:02:27"

mydt = now() 

MSGBOX Year(mydt)& Month(mydt)& Day(mydt)& Hour(mydt)& Minute(mydt)& second(mydt)

this returns "201522713227"

i need it to return "20150227130227" i could use a if < 10 but there must be a slicker way


Solution

  • Thanks to @Ekkehard.Horner and @Bagger

    I have reviewed your advice and have chosen to go with the below, adapted for my needs.

    I have chosen this one as it is a lot more useable/adaptable I can swap and change date formats as required.

    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
    
    '-------------------------------------------------------------------
    
    Dim dt : dt = now()
    
    WScript.Echo sprintf("{0:yyyyMMddhhmmss}", Array(dt))
    

    This returns the value in required format yyyyMMddhhmmss

    20150302110727
    

    If you just require date you would simply change the sprintf

    sprintf("{0:yyyyMMdd}", Array(dt))
    

    Just want the time

    sprintf("{0:hhmmss}", Array(dt))
    

    and so on.....