Format Time up to Milliseconds to use in log files [duplicate] - vbscript

This question already has answers here:
Find time with millisecond using VBScript
(3 answers)
Closed 5 years ago.
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.

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

Another way to do the same thing, with a bit less code. In this code, we're splitting Now() into an array so we can use it for everything except the milliseconds.:
WScript.Echo PrintTimeStamp()
Function PrintTimeStamp()
nowParts = SPLIT(Now(), " ")
timePart = nowParts(1)
t = Timer
milliseconds = Int((t-Int(t)) * 1000)
PrintTimeStamp = nowParts(0) & " " & LeftPad(nowParts(1), "0", 8) & "." & LeftPad(milliseconds, "0", 3) & " " & nowParts(2)
End Function
Function LeftPad(str, addThis, howMany)
LeftPad = String(howMany - Len(str), addThis) & str
End Function

Related

Why can't I set up a variable date in my VBScript which changes incrementally [duplicate]

This question already has answers here:
How to measure code execution time in VBScript or JavaScript?
(7 answers)
Closed 2 years ago.
I have a Vbscript which outputs the time taken for my anti-virus to update the signature version on a daily basis at 05:00 AM, before performing a scan. This is the script
Function TimeSpan(dt1, dt2)
If (isDate(dt1) And IsDate(dt2)) = false Then
TimeSpan = "00:00:00"
Exit Function
End If
seconds = Abs(DateDiff("S", dt1, dt2))
minutes = seconds \ 60
hours = minutes \ 60
minutes = minutes mod 60
seconds = seconds mod 60
if len(hours) = 1 then hours = "0" & hours
TimeSpan = hours & ":" & _
RIGHT("00" & minutes, 2) & ":" & _
RIGHT("00" & seconds, 2)
End Function
d1 = LAST_UPDATE
d2 = 22 Jul 20 05:00:00AM
d1 [ LAST_UPDATE ] is the time the update is completed, so what I need is the starting time. The script runs accurately as long as I incorporate the date and time in ' d2 ' [ as shown in the script ]. This means that to output the result on a daily basis, I have to open the vbscript and change the date to current date [ the time remains constant at 05:00:00 AM ]
The output result is given to me after 10 minutes.
I have tried using ' Now ()' but this output includes the time taken from the time the update is completed and the 10 minutes [ that has lapsed ] till the result is provided. This doesnot serve the purpose of this script.
What I am trying to get at is, is there a way which can be incorporated in the script itself,[ with another fuction or so ] which will change the date [ to tomorrow ] and the time [ the time remains constant at 05:00:00 AM ] incrementally after every 24 hours at 12:00:00 AM in the script itself keepiing it ready for the next day's operation without any user action of changing the date manually
I have tried all ways possible to resolve this but have failed. My efforts always culminate in ' Now() ' and the entire excercise is wasted.
Any help will be appreciated.This is the script
Rajdeep
If you simply want to measure the time it takes for the anti-virus update to run, you can use the Timer function like this:
Dim sngStart
Dim sngTimeSpan
sngStart = Timer
' Do work here
sngTimeSpan = Timer - sngStart
sngTimeSpan is a value in seconds.
You can do the same with the Now function:
Dim dStart
dStart = Now
' Do work here
seconds = Abs(DateDiff("S", dStart, Now))
Essentially you are calling Timer or Now twice and calculating the difference between the two, eliminating the need for the d2 variable.
Here's a complete example using a MsgBox to simulate some task being performed:
Dim sngStart
Dim sngEnd
Dim sngSecondsElapsed
Dim iSecondsElapsed
Dim dStart
' Grab system Timer and current time
sngStart = Timer
dStart = Now
' Simulating a delay here by displaying a message box
MsgBox "Click OK after a few moments"
' Calculate seconds elapsed
sngSecondsElapsed = Timer - sngStart
iSecondsElapsed = Abs(DateDiff("S", dStart, Now))
MsgBox "Seconds Elapsed:" & vbCrLf & "Timer method: " & FormatNumber(sngSecondsElapsed, 2) & vbCrLf & "Now method: " & iSecondsElapsed

Date issue in vb script [duplicate]

This question already has an answer here:
Format current date and time in VBScript
(1 answer)
Closed 4 years ago.
My issue is when I retrieve date back it gives me in this format:
lastseenstatus=rsprefobj("lastseentstamp")
19-07-2014 15:31:32
I want it in 7/19/2014 3:31:32 PM format with AM/PM intact.
Please help..
First and foremost you need to determine the data type of rsprefobj("lastseentstamp"):
MsgBox TypeName(rsprefobj("lastseentstamp"))
If it's a string, you need to convert it to a datetime value first:
lastseenstatus = CDate(rsprefobj("lastseentstamp"))
If you want the date formatted according to the system's regional settings, use the FormatDateTime() function as #John suggested:
MsgBox FormatDateTime(lastseenstatus)
If you need a distinct date format regardless of the system's regional settings you have to either build the formatted string yourself:
Function LPad(v) : LPad = Right("00" & v, 2) : End Function
Function FormatDate(d)
formattedDate = Month(d) & "/" & LPad(Day(d)) & "/" & Year(d) & " " & _
((Hour(d) + 23) Mod 12 + 1) & ":" & LPad(Minute(d)) & ":" & _
LPad(Second(d))
If Hour(d) < 12 Then
formattedDate = formattedDate & " AM"
Else
formattedDate = formattedDate & " PM"
End If
FormatDate = formattedDate
End Function
MsgBox FormatDate(lastseenstatus)
or use the .Net StringBuilder class:
Set sb = CreateObject("System.Text.StringBuilder")
sb.AppendFormat "{0:M\/dd\/yyyy h:mm:ss tt}", lastseenstatus
MsgBox sb.ToString()
In my tests I wasn't able to get the tt format specifier to work, though, so you may have to resort to something like this:
Set sb = CreateObject("System.Text.StringBuilder")
If Hour(lastseenstatus) < 12 Then
am_pm = "AM"
Else
am_pm = "PM"
End If
sb.AppendFormat_5 Nothing, "{0:M\/dd\/yyyy h:mm:ss} {1}", _
Array(lastseenstatus, am_pm)
MsgBox sb.ToString()
I'm assuming you are using VBScript and not VB.NET like you have tagged.
Use FormatDateTime(lastseenstatus).
That should give you the format "2/16/2010 1:45:00 PM".

UTC Time Assignment in VBScript

Does anyone have a simple means in VBScript to get the current time in UTC?
Thanx,
Chris
I use a simple technique
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate (now())
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & dateTime.GetVarDate (false)
More info on SWbemDateTime
If you wanted to convert UTC back to local time do this:
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate now(),false REM Where now is the UTC date
wscript.echo cdate(dateTime.GetVarDate (true))
There are lots of examples out there. If you can access the registry this one will work for you:
od = now()
set oShell = CreateObject("WScript.Shell")
atb = "HKEY_LOCAL_MACHINE\System\CurrentControlSet\" &_
"Control\TimeZoneInformation\ActiveTimeBias"
offsetMin = oShell.RegRead(atb)
nd = dateadd("n", offsetMin, od)
Response.Write("Current = " & od & "<br>UTC = " & nd)
From http://classicasp.aspfaq.com/date-time-routines-manipulation/how-do-i-convert-local-time-to-utc-gmt-time.html
You can get time bias from Win32_TimeZone WMI class.
myDate = "9/4/2013 17:23:08"
For Each objItem In GetObject(_
"winmgmts:\\.\root\cimv2").ExecQuery(_
"Select * from Win32_TimeZone")
bias = objItem.Bias
Next
myDate = DateAdd("n", bias, myDate)
WScript.Echo myDate
With SetVarDate the offset change due to transition to daylight saving time (from +060 to +120) occurred one hour too soon. The RegRead(HKLM\..\ActiveTimeBias) method was spot-on. If reproduction is desired, just put the pc clock on a time just before and just after the expected transition time and check the results.
Here is an example that formats the date to UTC as well. Note that you cannot format to a millesecond level with this.
Dim formattedDate
Dim utcDate
Set objShell = WScript.CreateObject("WScript.Shell")
Set dateTime = CreateObject("WbemScripting.SWbemDateTime")
dateTime.SetVarDate(now())
utcDate = dateTime.GetVarDate(false)
wscript.echo "Local Time: " & dateTime
wscript.echo "UTC Time: " & utcDate
formattedDate = DatePart("yyyy",utcDate) & "-" & Right("0" & DatePart("m",utcDate), 2) & "-" & Right("0" & DatePart("d",utcDate), 2)
& "T" & Right("0" & DatePart("h",utcDate), 2) & ":" & Right("0" & DatePart("n",utcDate), 2)
& ":" & Right("0" & DatePart("s",utcDate), 2) & ".000+0000"
wscript.echo formattedDate
'results in a format that looks like this: 1970-01-01T00:00:00.000+0000
set dateTime=Nothing
set objShell=Nothing
Based on above functions - returns a delta-value to be added to the current time to return UTC.
Or call it with DATE+TIME to return UTC.
Call it once and store in a global variable to offset any date/time to UTC.
Conversely Subtract it from any UTC to get the time in the current time zone.
The additional ROUND towards the bottom is an attempt to compensate for floating point errors in the conversion to the nearest second.
Function Time_add_To_get_UTC(Optional DateTime = 0) ''as double
'' Returns value to add to current time to get to UTC
''Based on above functions : )
''return offset from current time to UTC
''https://stackoverflow.com/questions/15887700/utc-time-assignment-in-vbscript/22842128
Dim SWDT ''As SWbemDateTime
Dim dt ''As Date
Set SWDT = CreateObject("WbemScripting.SWbemDateTime")
dt = Date + Time()
SWDT.SetVarDate (dt)
Time_add_To_get_UTC = CDbl(SWDT.GetVarDate(False)) - CDbl(SWDT.GetVarDate(True))
Time_add_To_get_UTC = CDbl(Round(Time_add_To_get_UTC * 24 * 60 * 60, 0) / 24 / 60 / 60)
Time_add_To_get_UTC = DateTime + Time_add_To_get_UTC
End Function

DateDiff vbscript to find current date files

I need vbscript to iterate files through files and find all files which are created today.
DateDiff("d",RFile.DateLastModified ,Date)=0
I can see there are 40 files in the folder for today but when the script scans though all files, it lists files less than 40. Maybe it is also looking at the time portion.
Can anyone tell me exactly how to use the datediff function so that I can achieve the desired.
I want it to get all files whose DATE portion is today's date portion without any consideration for the time portion.
When you create a datetime value without a time portion in VBScript, the time is automatically assumed to be 00:00:00 (see for instance the return value of TimeValue(Date)). Because of this DateDiff() compares the "last modified" timestamp of the file with the current date at 00:00:00 and returns a value greater than 1 (or less than -1) when the difference exceeds ±24 hours.
For comparing just the date parts of two timestamps use the FormatDateTime() function:
today = FormatDateTime(Date, vbShortDate)
If FormatDateTime(RFile.DateLastModified, vbShortDate) = today Then
'...
End If
Your better off just enumarating the files with WMI manupulating the date to just compare the day month and year attributes ignoring the time stamp.
strComputer = "."
Set objWMIService = GetObject("winmgmts:" _
& "{impersonationLevel=impersonate}!\\" & strComputer & "\root\cimv2")
Set colFiles = _
objWMIService.ExecQuery("Select * From CIM_DataFile Where Drive = 'E:' and Path = '\\Test\\'")
For Each objFile in colFiles
dtCreationDate = WMIDateStringToDate(objFile.CreationDate)
If Day(Now)&Month(Now)&Year(Now) = Day(dtCreationDate)&Month(dtCreationDate)&Year(dtCreationDate) Then
WScript.Echo objFile.Name
End If
Next
Function WMIDateStringToDate(sCreatoionDate)
WMIDateStringToDate = CDate(Mid(sCreatoionDate, 7, 2) & "/" & _
Mid(sCreatoionDate, 5, 2) & "/" & Left(sCreatoionDate, 4) _
& " " & Mid (sCreatoionDate, 9, 2) & ":" & _
Mid(sCreatoionDate, 11, 2) & ":" & Mid(sCreatoionDate, 13, 2))
End Function

Find time with millisecond using VBScript

I want to get time with millisecond
Currently using Timer() method but it just give access upto second
Any idea?
Please make sure i don't want to convert second into millisecond want to get with millisecond
In fact Timer function gives you seconds with milliseconds. Integer part of returned value is the number of seconds since midnight and the fraction part can be converted into milliseconds - just multiply it by 1000.
t = Timer
' Int() behaves exactly like Floor() function, i.e. it returns the biggest integer lower than function's argument
temp = Int(t)
Milliseconds = Int((t-temp) * 1000)
Seconds = temp mod 60
temp = Int(temp/60)
Minutes = temp mod 60
Hours = Int(temp/60)
WScript.Echo Hours, Minutes, Seconds, Milliseconds
' Let's format it
strTime = String(2 - Len(Hours), "0") & Hours & ":"
strTime = strTime & String(2 - Len(Minutes), "0") & Minutes & ":"
strTime = strTime & String(2 - Len(Seconds), "0") & Seconds & "."
strTime = strTime & String(4 - Len(Milliseconds), "0") & Milliseconds
WScript.Echo strTime
This uses the standard dateserial in vbs
'get a timeserial with milliseconds
d1= date+ timer/86400
Wscript.echo datestamp(d1)&" "& timestamp(d1)
function datestamp(d)
datestamp=year(d) &"/"& month(d) & "/" & day(d)
end function
function timestamp(d)
ymd=fix(d)
h=hour(d)
m=minute(d)
s=second(d)
timestamp=right("00" & h,2)&":"& right("00" & m,2)& ":" & right("00" & s,2)& ","& _
right("000"& 86400000*(d-timeserial(h,m,s)-ymd),3)
end function
Building upon MBu's answer, here's a Sub version. Sprinkle calls to this around your code for messages in the immediate window, so you can see where delays are happening.
' *** Debug.Print the time with milliseconds, and a message of your choice
Private Sub DebugPrintTime(strWhereFrom As String)
On Error GoTo ErrHandler
Dim sglTimer As Single
Dim sglWholeSecs As Single
Dim Millisecs As Variant ' as a variant, Len() will give the length of string representation of this value
Dim Seconds As Variant
Dim Minutes As Variant
Dim Hours As Variant
Dim strTime As String
sglTimer = timer
sglWholeSecs = Int(sglTimer)
Millisecs = Int((sglTimer - sglWholeSecs) * 1000)
Seconds = sglWholeSecs Mod 60
sglWholeSecs = Int(sglWholeSecs / 60)
Minutes = sglWholeSecs Mod 60
Hours = Int(sglWholeSecs / 60)
strTime = String(2 - Len(Hours), "0") & Hours & ":"
strTime = strTime & String(2 - Len(Minutes), "0") & Minutes & ":"
strTime = strTime & String(2 - Len(Seconds), "0") & Seconds & "."
strTime = strTime & String(3 - Len(Millisecs), "0") & Millisecs
Debug.Print strTime, strWhereFrom
Exit Sub
ErrHandler:
MsgBox "Error in Sub DebugPrintTime" & vbCrLf & Err.Description & vbCrLf & strWhereFrom
Err.Clear
End Sub

Resources