how to convert a number into mm:ss format using VBScript - time

I want to convert a number (less than 3600) in mm:ss format using VBScript. The main issue that i am facing is to add leading zeroes in case i get a single digit.
For example:-
while trying to convert 306 in mm:ss format i get the output as 5:6 instead of 05:06.
This is my code..
entered_time = "306"
quotient = entered_time/60
quotient = Int(quotient)
MsgBox quotient
remainder = entered_time Mod 60
MsgBox remainder
time_format = quotient&":"&remainder
msgbox time_format
Thanks for the help in advance.

Try like this ;)
intTotalSecs = 306
MsgBox intTotalSecs & "(s) ===> " & ConvertTime(intTotalSecs),vbinformation,"output time format as hh:mm:ss"
'************************************************************
Function ConvertTime(intTotalSecs)
Dim intHours,intMinutes,intSeconds,Time
intHours = intTotalSecs \ 3600
intMinutes = (intTotalSecs Mod 3600) \ 60
intSeconds = intTotalSecs Mod 60
ConvertTime = LPad(intHours) & " h : " & LPad(intMinutes) & " m : " & LPad(intSeconds) & " s"
End Function
'************************************************************
Function LPad(v)
LPad = Right("0" & v, 2)
End Function
'************************************************************

What about a simple if remainder < 10 ?

If your locale/regional settings are suitable, you just do:
>> setlocale "de-de"
>> secs = 308
>> ts = TimeSerial(0, 0, secs)
>> WScript.Echo FormatDateTime(ts, vbLongTime)
>>
00:05:08
If that's not possible, put some effort in a .NET based format class like this one.

Related

VBS Msgbox(DateTime.Now.ToString("yyyyMMdd HH:mm:ss")) show error

Please help. My code just simple but show error as in the picture.
Msgbox DateTime.Now.ToString("yyyyMMdd HH:mm:ss")
There is no DateTime object in VBScript, just plain Date variables and functions:
>> d = Date()
>> n = Now()
>> WScript.Echo TypeName(d), d, TypeName(n), n
>> WScript.Echo TypeName(Month(n)), Month(n)
>> s = FormatDateTime(n)
>> WScript.Echo TypeName(s), s
>>
Date 21.06.2017 Date 21.06.2017 05:58:13
Integer 6
String 21.06.2017 05:58:13
You can use a .NET System.Text.StringBuilder to do more fancy formatting. (cf here)

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

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

How to remove the seconds from timeValue function

I'm looking to print out the time 6:00am without the seconds. Using TimeValue it includes the seconds. Is there away to do this without including the seconds?
CurrentTime = TimeValue("6:00 am")
Use built-in FormatDateTime with vbShortTime :
CurrentTime = FormatDateTime("6:00:31 am", vbShortTime)
Use a RegExp to zap the offending seconds from the string representation of the date:
>> Set r = New RegExp
>> r.Pattern = ":\d\d "
>> dtCurrentTime = TimeValue("6:00 PM")
>> sCurrentTime = CStr(dtCurrentTime)
>> sCurrentTime = r.Replace(sCurrentTime, " ")
>> WScript.Echo qq(sCurrentTime)
>>
"6:00 PM"
dtCurrentTime = TimeValue("6:00 PM")
sCurrentTime = CStr(dtCurrentTime)
sCurrentTime=Replace (sCurrentTime,":00:00 PM",":00 PM")
MsgBox sCurrentTime
I had the same problem. But I use Mid, Left & Right functions to solve it.
ThisTime = TimeValue(YourTime)
TimeSpace = InStr(1,ThisTime," ")
ThisShortTime = Left(ThisTime,TimeSpace-4) & Right(ThisTime,3)
InStr looks for the space within the time.
Left picks up the left side of the time, minus the second.
Right picks up the last 3 characters of the time, eg " AM" or " PM".

Replace # in vb script

I have this line in vb script:
fileCheck = Right(objLookFile.name, len(objLookFile.name) - len("Audit_######_"))
the Audit_######_ takes 6 digits for now. I got a situation where I have files with 7 digits and 8.
ex of file : Audit_1002611_Comnpany_MTH_11_2013.00001.txt
How I change the ###### to accept any number of digits?
dim lookFor
lookFor = fiRef(i_fi) & "_" & AIOType(i_type) & "_" & Right("00" & (month(processDate + 1)), 2) & "_" & Year(processDate + 1) & ".00001.txt"
dim minLen
minLen = len(lookFor)
dim objLookFolder, objLookFile
set objLookFolder = objFSO.GetFolder(AIODVDDir)
For each objLookFile in objLookFolder.files
if Len(objLookFile.name) >= minLen then
dim fileCheck
fileCheck = Right(objLookFile.name, len(objLookFile.name) - len("Audit_######_"))
if (Left(objLookFile.name, len("Audit_")) = "Audit_") AND (fileCheck = LookFor) then
'found the audit file
Thank you
Well, you're not doing anything with "Audit_######_" other than getting it's length. It looks like a hack-y way to just strip off the first 13 characters.
A smarter way may be to get everything after the second underscore :
fileCheck = mid(objLookFile.name, instr( instr(objLookFile.name, "_") + 1 , "_")+1)
There are several ways to handle this. Using string operations as D Stanley suggested is one way. Another is to split the file name at underscores and examine the fragments:
arr = Split(objLookFile.Name, "_", 3)
If UBound(arr) = 3 Then
If arr(0) = "Audit" And IsNumeric(arr(1)) And arr(2) = lookFor Then
...
End If
End If
Using a regular expression is probably the best approach, though:
Set re = New RegExp
re.Pattern = "Audit_\d+_" & fiRef(i_fi) & "_" & AIOType(i_type) _
& "_" & Right("00" & (month(processDate + 1)), 2) _
& "_" & Year(processDate + 1) & "\.00001\.txt"
For Each objLookFile In objFSO.GetFolder(AIODVDDir).Files
If re.Test(objLookFile.Name) Then
...
End If
Next
\d+ will match one or more digits. If you want to match a limited number of digits (e.g. at least 6 and at most 8 digits) replace that part of the pattern with \d{6,8}.

Faster Way To Examine Text in AutoIt?

I'm attempting to use AutoIt to examine a text file and output select lines into a CSV. The problem I keep running into is that it takes forever. The current method examines a single line at a time. It can burn through 5-10 lines per second, but I'm looking for something much faster within the AutoIt framework.
Code:
#include <File.au3>
$xnConfirm = False
$xnConfirmMsg = 0
while $xnConfirm = False
$xnFile = FileOpenDialog("File to Examine...","%userprofile%","All (*.*)") ;InputBox("File???", "Which file do you want to review?","C:\")
If FileExists($xnFile) = True Then
$xnConfirm = True
Else
$xnConfirmMsg = msgbox(1,"File Not Found...",$xnFile & " does not exist." & #crlf & "Please select another file.")
EndIf
WEnd
$xnConfirm = False
$xnConfirmMsg = 0
while $xnConfirm = False
$xnTargetFile = FileOpenDialog("Location to Save to...",$xnFile & " - output.csv","All (*.*)");"%userprofile%\Documents\output.csv"
;FileSaveDialog("Location to Save to...","%userprofile%","All (*.*)",16,"output - " & $xnFile & " - output.csv") ;
Consolewrite("Outputting to " & $xnTargetFile & #crlf)
if fileexists($xnTargetFile) then
$xnConfirmMsg = msgbox(4,"Overwrite?","Are you sure you want to overwrite " & #crlf & $xnTargetFile)
if $xnConfirmMsg = 6 Then
$xnConfirm = True
filedelete($xnTargetFile)
EndIf
Else
$xnConfirm = True
EndIf
WEnd
progresson("Line count","Verifying the number of lines in " & $xnFile)
$xnFileLine = _FileCountLines($xnFile) ;InputBox("Number of lines","How many lines are in this document?",10000)
consolewrite("Loading "& $xnFile & " with " & $xnFileLine & " total lines." & #crlf)
progressoff()
local $hfl = FileOpen($xnFile,0)
FileWrite($xnTargetFile,"")
FileOpen($xnTargetFile, 1)
$i = 1
ProgressOn("Creating CSV","Extracting matching data.","",0,0,16)
$xnTargetLine = 1
FileWriteLine($xnTargetFile,"Timestamp,Message,Category,Priority,EventId,Severity,Title,Machine,App Domain,ProcessID,Process Name,Thread Name,Win32 ThreadId")
While $i < $xnFileLine
;$xnCurrentLine = FileReadLine($xnFile,$i) ;Old Settings
$xnCurrentLine = FileReadLine($hfl,$i)
;MsgBox(1,"",$xnCurrentLine)
Select
Case stringinstr($xnCurrentLine,"Timestamp:")
$xnTargetLine = stringmid($xnCurrentLine,12,stringlen($xnCurrentLine) - 12 + 1) & ","
Case stringinstr($xnCurrentLine,"Message:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,10,stringlen($xnCurrentLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,11,stringlen($xnCurrentLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,16,stringlen($xnCurrentLine) - 16 + 1) & #crlf
FileWriteLine($xnTargetFile,$xnTargetLine)
case Else
consolewrite("Nothing on line " & $i & #crlf)
EndSelect
$i = $i + 1
ProgressSet(round($i/$xnFileLine * 100,1),$i & " of " & $xnFileLine & " lines examined." & #cr & "Thank you for your patience.")
WEnd
ProgressOff()
To address the question of what this is doing, I'm reading a log file similar to a trace log. I want the events to output to a CSV so I can examine trends. The format in the log file looks like this:
Timestamp: 9/26/2013 3:33:23 AM
Message: Log Event Received
Category: Transaction
Win32 ThreadId:2872
I know that's the code format, but I hope it's easier to read.
(I wanted to add a comment asking for a sampling of the data being read in, however I don't have enough points yet...)
Depending on the size of the input file I recommend reading the entire file into an array in one swoop using _FileReadToArray() and then looping through the array in memory (instead of keeping access to the file open during the entire process). In addition, I wouldn't write to the output file each time either - I'd write to a string and then save the string when completed.
Something like:
$outputFileData = ""
$inputFileData = _FileReadToArray($xnFile)
For $Counter = 1 to $inputFileData[0]
$tmpLine = $inputFileData[$Counter]
Select
Case stringinstr($tmpLine,"Timestamp:")
$outputFileData = stringmid($tmpLine,12,stringlen($tmpLine) - 12 + 1) & ","
Case stringinstr($tmpLine,"Message:")
$outputFileData &= stringmid($tmpLine,10,stringlen($tmpLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$outputFileData &= stringmid($tmpLine,11,stringlen($tmpLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$outputFileData &= stringmid($tmpLine,16,stringlen($tmpLine) - 16 + 1) & #CRLF
case Else
ConsoleWrite("Nothing on line " & $i & #crlf)
EndSelect
Next
FileWriteLine($xnTargetFile, $outputFileData)
(Please note I didn't include any error checking nor did I check it for errors :)
Im not sure if it would be really faster but, you could use Regexp.
If you could tell me a little bit more what the rules are here:
Case stringinstr($xnCurrentLine,"Timestamp:")
$xnTargetLine = stringmid($xnCurrentLine,12,stringlen($xnCurrentLine) - 12 + 1) & ","
Case stringinstr($xnCurrentLine,"Message:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,10,stringlen($xnCurrentLine) - 10 + 1) & ","
Case stringinstr($xnCurrentLine,"Category:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,11,stringlen($xnCurrentLine) - 11 + 1) & ","
Case stringinstr($xnCurrentLine,"Win32 ThreadId:")
$xnTargetLine = $xnTargetLine & stringmid($xnCurrentLine,16,stringlen($xnCurrentLine) - 16 + 1) & #crlf
FileWriteLine($xnTargetFile,$xnTargetLine)
case Else
consolewrite("Nothing on line " & $i & #crlf)
and if you could give me 2 or 3 example lines i could try to make you a, Regexp function wich i think will be much faster.
Edit:
I Made an example Script.
If the Input File looks something like this:
Timestamp: 9/26/2013 3:33:23 AM
Message: Log Event Received
Category: Transaction
Win32 ThreadId:2872
Then This Script works just fine
#include <Array.au3>
Local $file = FileOpen("InputFile.txt", 0)
$sText = FileRead($file)
$aSnippets = StringRegExp($sText,"(?:Timestamp:|Message:|Category:|Win32 ThreadId:)(?: )?(.+)",3)
_ArrayDisplay($aSnippets)
The result is an array Containing the Following things:
[0] = 9/26/2013 3:33:23 AM
[1] = Log Event Received
[2] = Transaction
[3] = 2872
etc.
If you want to combine these 4 lines in one, try to use a for loop (if you want to, i can make you one)
For 100 Lines he Needs 0.490570878768441 Miliseconds to store every Value in one array.
There is an other possible idea.
You could copy the Input File, rename it, and then Delete every useles Data out of it.
That would be very easy with RegularExpressions and probably even faster.
If you show me a example of the Input File and how the Output file should look like i could try :)

Resources