Search code examples
vbscriptmilliseconds

Format Time up to Milliseconds to use in log files


My VBScript has a log file which logs information with current date and time using FormatDateTime Function.

I like to format time up to milliseconds and also in the following format:

MM/DD/YY hh:mm:ss:mss AM/PM

But, unfortunately FormatDateTime doesn't let to format time in this way. After searching for this, I found this answer and it is about how to use Timer function, So I can't log time to log files using it again and again.

As W3schools states,

The Timer function returns the number of seconds since 12:00 AM.

But I want my log file to log time in above format even before 12:00 AM, So using Timer Function isn't the best option for this.

Please let me know a way to do this specially in log files correctly.


Solution

  • The vbscript function Now() will return the current system date and time in this format - 5/2/2017 9:45:34 AM, however if you need to add milliseconds you can use Timer - Timer math from here

    'capture the date and timer together so if the date changes while 
    'the other code runs the values you are using don't change
    t = Timer
    dateStr = Date()
    temp = Int(t)
    
    milliseconds = Int((t-temp) * 1000)
    
    seconds = temp mod 60
    temp    = Int(temp/60)
    minutes = temp mod 60
    hours   = Int(temp/60)
    label = "AM"
    
    If hours > 12 Then
        label = "PM"
        hours = hours-12
    End If
    
    'format it and add the date
    strTime = LeftPad(hours, "0", 2) & ":"
    strTime = strTime & LeftPad(minutes, "0", 2) & ":"
    strTime = strTime & LeftPad(seconds, "0", 2) & "."
    strTime = strTime & LeftPad(milliseconds, "0", 3)
    
    
    WScript.Echo dateStr & " " & strTime & " " & label
    
    'this function adds characters to a string to meet the desired length
    Function LeftPad(str, addThis, howMany)
        LeftPad = String(howMany - Len(str), addThis) & str
    End Function