Click here to Skip to main content
Click here to Skip to main content

Use Date & Time in Batch/Log Files

By , 1 Feb 2008
 

Introduction

Have you ever tried to use date and time in logfiles or batch/command files?
This is not easy without special software. For me, this was a problem because I needed a separate logfile every time an event happened. I also needed this to create backup schedules. The possibilities of batch command are too limited, and different language OS will react differently, so it is hard to roll such batch files out in a multi language OS environment.

Solution

The solution is very simple. I run a VB script where it is easy to get date time and other parameters. These values are stored in environment variables which can be used in batch files.
Because these environment variables are only valid in that particular shell, we need to call the batch file within the VB Script.

Copy the following code in a file called RunNow.cmd:

'***********************************************
'
' RunNow.vbs
' (c) 2008 Computech.
'     Initially Version 2003.
'     2/2/2008 Extra Functionality
' Written by Peter Verijke
'
'***********************************************
Dim dDay, dLDOM, dLDOY, dLFOW, dLFOM
Dim ArgObj
Dim BatchFile
Dim sCommand

Dim WshShell ' as object
Dim objEnv ' as collection
Dim sGetMyVar  ' as string

' Get the Arguments object
Set ArgObj = WScript.Arguments

' Test to make sure there is at least one command line arg - the command
If ArgObj.Count < 1 Then
    DisplayHelpMessage
    WScript.Quit
End If

BatchFile = ArgObj(0)

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objEnv = WshShell.Environment("PROCESS")

dNow = Now()
dLDOM = DateSerial(Year(dNow),Month(dNow) + 1,0)
dLDOY = DateSerial(Year(dNow) + 1, 1,0)
'Friday of this week
dLFOW = (dNow + (5 - Weekday(dNow, vbMonday)))
'Last Friday of Month
dLFOM = (dLDOM + (5 - Weekday(dLDOM, vbMonday)))

objEnv("Year") = Year(dNow)
objEnv("Month") = Right("0" & Month(dNow), 2)
objEnv("Day") = Right("0" & Day(dNow), 2)
objEnv("Hour") = Right("0" & Hour(dNow), 2)
objEnv("Minute") = Right("0" & Minute(dNow), 2)
objEnv("Second") = Right("0" & Second(dNow), 2)

'Day of Week
objEnv("DOW") = Weekday(dNow, vbMonday)
'Day of Week Name
objEnv("DOWN") = WeekDayName(WeekDay(dNow), 1)
'Week of Month
objEnv("WOM") = -Int(-((WEEKDAY(dNow-DAY(dNow)+1, 2) + DAY(dNow) -1) / 7))
'Last Day of Month
objEnv("LDOM") = Right("0" & Day(dLDOM), 2)
'Last Day of Year
objEnv("LDOY") = Right("0" & Day(dLDOY), 2)
'Last Friday of Week
objEnv("LFOW") = Right("0" & Day(dLFOW), 2)
'Last Friday of Month
objEnv("LFOM") = Right("0" & Day(dLFOM), 2)

sCommand = "%COMSPEC% /C " 

WshShell.Run(sCommand + BatchFile) 

WScript.Quit

'************************
'
' Display Help Message
'
'************************
Sub DisplayHelpMessage()
    Dim sHelpMessage
    sHelpMessage = "Usage:" & vbCrLf
    sHelpMessage = sHelpMessage & Wscript.FullName & _
	" RunNow <CommandFile|BatchFile>" & vbCrLf
    sHelpMessage = sHelpMessage & _
	"Optionally use environment variables in file: _
	%Year% %Month% %Day% %Hour% %Minute% %Second%" & vbCrLf
    sHelpMessage = sHelpMessage & _
	"%DOW% %DOWN% %WOM% %LDOM% %LDOY% %LFOW% %LFOM%" & vbCrLf
    WScript.Echo sHelpMessage
End Sub

Usage

As you can see in the source Help Message, it is sufficient to use the environment variables %Year% %Month% %Day% %Hour% %Minute% or %Second% in your batch files. To give an example: you could make a command file called mydir.cmd with the following contents:

dir > MyLog%Year%%Month%%Day%-%Hour%%Minute%%Second%.log 

Instead of running this file directly, run via the VB Script:

RunNow.vbs mydir.cmd 

Now, there are also some extra environment variables like Last Day of Month, Week of Month etc. These variables can also be used for naming or comparing to take other actions in batch files. I use it to create Day, Week and Month Backups for some data.

That's it.

I hope this will be useful to you.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Peter Verijke
Founder Computech bvba
Belgium Belgium
Member
I´m a freelance ICT consultant and Technical Project Manager for the last 15 years already.
Before that, I was a Software Developer for the Pharmaceutical and Petrochemical industry.
I developed a very wide knowledge in the ICT world due to my intrest.
This includes Networking (Lan, Wan), Routing Switching Bridging, etc...
Windows environment, which has no secrets for me.
Developing: To many languages to mension here.
Of course, the latest one on the list is dot net.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralJust made use of thismemberOffbeatmammal31 Dec '08 - 10:30 
Neat script - thanks.
 
I've just made use of it (see example here) and I added another environment variable
 
'MonthName
objEnv("MN") = MonthName(Month(dNow))
 
Regards
 
~Offbeatmammal
Questionhow can i use this?memberblajarbot4 Jan '07 - 20:26 
i'm new for this asp language.. i want to use this as my final project in my study...
could you explain it to me how i can use it? step by step...
i already try to copy & paste it to notepad and save it as runnow.cmd and mydir.cmd
but at the bottom line you wrote that use via vbscript.. i dont get it.. runnow.vbs ?
.cmd or .vbs ? thanks for the help..
 
ordinary man looking for better future

GeneralAM or PMsussAnonymous22 Jan '05 - 16:03 
I hope you can put AM or PM to the code.
Please its important to me.
GeneralRe: AM or PMsussAnonymous22 Jan '05 - 16:39 
:::I hope you can put AM or PM to the code.
:::Please its important to me.
 
problem solved!
anyway thanks to you all guys.
nice tips and code.
GeneralRe: AM or PMmember____0113 Jan '07 - 16:44 
hiiiiiiii.............. can i ask for the code for AM or PM?
QuestionCan be done with batch commands alonememberPaul Bartlett17 Dec '03 - 23:27 
If you have command extensions enabled, then DATE /T will display the date. You can make use of this with the FOR /F command, e.g.
 
FOR /F "tokens=1-3 delims=/ " %a IN ('DATE /T') DO SET FILENAME=Log%c%b%a.txt
 
will execute the command: SET FILENAME=Log20031218.txt (if you've got UK English date formats).
 
Note that in a batch file, the a, b and c variables need two percent signs, i.e. %%a, %%b and %%c wherever they appear
AnswerRe: Can be done with batch commands alonememberRabidCow18 Dec '03 - 9:11 
(from the help for the set command)
 
%DATE% - expands to current date using same format as DATE command.
 
%TIME% - expands to current time using same format as TIME command.
 
So:
 
set f=%date:/=%%time::=%
:: Thu 12182003120939.93
set f=Log%f:~8,4%%f:~4,4%-%f:~12,6%.txt
:: Log20031218-120939.txt

GeneralRe: Can be done with batch commands alonememberfunny thing18 Dec '03 - 9:54 
Guys, he's a consultant, he has to write *something* regardless of whether it's needed or not. C'mon, give him a break
 
LOL
GeneralRe: Can be done with batch commands alonememberPeter Verijke18 Dec '03 - 23:13 
RabidCow,
 
Well done, nice. But my answer is the same as to Paul.
There are no guaranties this will work, because of regional settings.
This will only work if your regional settings are set ok.
In my case I have to adapt the second command line.
Difference with Paul his method is that you do have seconds here.
 
The VBscript method works independant of the regional settings.
 
Regards
Peter
GeneralRe: Can be done with batch commands alonesussAnonymous25 Mar '05 - 0:36 
REM Get Date as YYYYMMDD
Date/t | findstr /I / && Goto English
for /F "tokens=1-3 delims=. " %%i in ('Date/t') do Set ToDay=%%k%%j%%i
Goto Label
 
:English
for /F "tokens=1-3 delims=/ " %%i in ('Date/t') do Set ToDay=%%k%%i%%j
 
:Label

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 1 Feb 2008
Article Copyright 2003 by Peter Verijke
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid