[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More


Using dates in batch files / scripts

Published on
50,936 Points
13 Endorsements
Last Modified:
Community Pick
Using dates in 'DOS' batch files has always been tricky as it has no built in ways of extracting date information.  There are many tricks using string manipulation to pull out parts of the %date% variable or output of the date /t command but these rely heavily on the regional settings of the user the script is running as.

If a quick and dirty date or time stamp for a filename, for instance, is required you can use some simple character substitution to amend the date / time entries to remove the / and : characters so that they can be used in a filename, e.g.

set filename="File %date:/=-%%time::=-%".txt

Open in new window

results in a filename like  "File 09-07-2009 9-37-42.40.txt"
or "File Thu 09-07-2009 9-37-42.40.txt"
or "File Thu 07-09-2009 9-37-42.40.txt"
or "File 07-09-2009 9-37-42.40.txt"
which is why extracting strings from a date is unreliable.

VBScript can be be used to extract day names, parts of the date etc. and combined into a batch file by using a for command to read the data ouput by a VB Script (amongst other ways).  This simple one line VBscript for instance returns all the various parts of a date that may be needed and can be used as in the example to construct a filename / path for instance:

wscript.echo weekdayname(weekday(date)) & "," & weekday(date) & "," & weekdayname(weekday(date),true) & "," & day(date) & "," & month(date) & "," & year(date) & "," & monthname(month(date),false) &"," & monthname(month(date),true) 

Open in new window

That could be called dateparts.vbs and stored somewhere for running or constructed on the fly from the batch file, e.g. in the user's temp folder.  All that is needed is to escape the & characters with a ^ and use redirection (>) to create a temporary VBS file:

@echo off
echo wscript.echo weekdayname(weekday(date)) ^& "," ^& weekday(date) ^& "," ^& weekdayname(weekday(date),true) ^& "," ^& day(date) ^& "," ^& month(date) ^& "," ^& year(date) ^& "," ^& monthname(month(date),false) ^&"," ^& monthname(month(date),true) > "%temp%\dateparts.vbs"

Open in new window

This can then be read using a for command taking the output from this file into environment variables:

for /f "tokens=1-8 delims=," %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set weekday=%%a& set weekdaynum=%%b& set shortday=%%c& set day=%%d& set month=%%e& set year=%%f& set monthname=%%g& set shortmonth=%%h

Open in new window

and displayed or used to make filenames, directories or compared to run differently depending upon the day -- e.g. run a full backup on a Friday etc.

echo Weekday:    %weekday%
echo weekdaynum: %weekdaynum%
echo shortday:   %shortday%
echo day:        %day%
echo month:      %month%
echo monthname:  %monthname%
echo shortmonth: %shortmonth%
echo year:       %year%
set filename="D:\files\%year%\%shortmonth%\Report for %day%-%month%-%year% (%weekday%).txt"
echo The filename is %filename%

Open in new window

If only certain parts are required the VBScript and/or batch file for command can be amended, e.g.

@echo off
echo wscript.echo weekday(date) ^& "," ^& day(date) ^& "," ^& month(date) ^& "," ^& year(date)  > "%temp%\dateparts.vbs"
for /f "tokens=1-4 delims=," %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set weekday=%& set day=%%d& set month=%%e& set year=%%f
if %weekday%==Fri echo It is Friday. & goto fullbackup
goto normalbackup
 echo Backing up to Z:\backups\weekly\%year%-%month%-%day%.zip
 rem backup commands
goto :eof
 echo Backing up to Z:\backups\daily\%year%-%month%-%day%.zip
 rem backup commands
goto :eof

Open in new window

Steve Knight
http://www.dragon-it.co.uk/ getdatebits.cmd.txt
LVL 44

Author Comment

by:Steve Knight
More details on how to return the parts you want from VBScript, this is Friday 4th September 2009:

Start a line with wscript.echo which means to send to the console whatever follows then whichever of the date components you need:

weekdayname(weekday(date))       Friday
weekday(date)                   6
weekdayname(weekday(date),true)       Fri
day(date)                        4
right(100+day(date),2)            04
month(date)                  9
right(100+month(date),2)            09
year(date)                  2009
right(year(date),2)                  09
monthname(month(date),false)      September
monthname(month(date),true)       Sep

combine those with

^& "," ^&

between each (to create this VBS from a batch file then before each & character you have to escape it with a ^)

The FOR loop will then send each entry from your comma seperated listed into %%a %%b %%c etc. which you can then assign to variables.

e.g. if you only need mm and yy then you could use:

echo wscript.echo right(100+month(date),2) ^& "," ^& right(year(date),2) >"%temp%\dateparts.vbs"
for /f "tokens=1-2 delims=," %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set mm=%%a& set yy=%%b
echo Year is %yy% and Month is %mm%
LVL 44

Author Comment

by:Steve Knight
To get yesterdays date use date-1  in place of date in any of the scripts...

@echo off
echo wscript.echo year(date - 1) ^& right(100 + month(date-1),2) ^& right(100+day(date-1 ),2)  > "%temp%\dateparts.vbs"
for /f "tokens=1 delims=" %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set yesterday=%%a
echo %yesterday%

or more generically this script will take a date from the command line formatted as YYYYMMDD and return the day before it - it creates a date in the VBScript using DateSerial then takes one off it then uses that date to output YYYYMMDD as above:

@echo off
if [%~1]==[] echo Usage: %0 YYYYMMDD returns the day before this date & pause & exit /b

REM Get date in yyyymmdd from command line as %1 and construct to use in
(echo nextday=DateSerial^(left^("%~1",4^),mid^("%~1",5,2^),mid^("%~1",7,2^)^)-1
echo wscript.echo year^(nextday^) ^& right^(100+month^(nextday^),2^) ^& right^(100+day^(nextday^),2^)
echo Remove these lines, just showing you the script it has created as VBScript after pressing any key
notepad "%temp%\getdate.vbs"

for /f "tokens=* delims=" %%a in ('cscript //nologo "%temp%\getdate.vbs"') do set thedate=%%a
echo %thedate%
LVL 17

Expert Comment

by:Kent Dyer
Notice you are using alot of VBS files..  How about in pure batch?




Note: Don't be too daunted by the following as it is heavily documented..



Rowby Goren Makes an Impact on Screen and Online

Learn about longtime user Rowby Goren and his great contributions to the site. We explore his method for posing questions that are likely to yield a solution, and take a look at how his career transformed from a Hollywood writer to a website entrepreneur.

LVL 44

Author Comment

by:Steve Knight
Agreed it CAN be done this way, the REG.EXE command is not in Windows 2000 or previous versions though for instance though it could be done using a regedit export and parsing the .REG file in those cases like in some of the examples.

All in all though a single line of VBScript I find easier to quickly add into a script when needed and remember how to write it if needed without having to lookup the script.

LVL 44

Author Comment

by:Steve Knight
LVL 44

Author Comment

by:Steve Knight
Some more prebuilt example scripts for common requests.
LVL 33

Expert Comment

Here's another way using the wmic utility.  I'm not sure when this utility first appeared in Windows, but it works in XP and later versions afaik:

Run this directly from a command prompt:

for /f "delims= " %C in ('wmic.exe path Win32_LocalTime Get Day^,Month^,Year /Format:List 2^>nul ^| find "="') do  set current%C

Open in new window

LVL 44

Author Comment

by:Steve Knight
End of Last month:

@echo off
REM Use VBScript to get date.  This will get the first day of this month and take one off to get last day of last month
(echo eolm=dateserial^(year^(date^),month^(date^),1^)-1
echo wscript.echo year^(eolm^) ^& right^(100 + month^(eolm^),2^) ^& right^(100+day^(eolm^),2^)) > "%temp%\dateparts.vbs"
for /f "tokens=1 delims=" %%a in ('cscript //nologo "%temp%\dateparts.vbs"') do set yyyymmdd=%%a

echo End of last month to use in filename was %yyyymmdd%


Open in new window

LVL 63

Expert Comment

by:Bill Prew
And of course, one of my preferred choices for date time formatting and math is DOFF, check it out at the link below.  It is a small utility program that you would need to have available to your BAT scripts, but I just keep a copy in a "util" folder that I include in my PATH.  Makes things very easy after that:

for /f "tokens=*" %%A in ('doff _yyyymmdd_hhmiss') do set dt=%%A

Open in new window

To get yesterday date you can simply do:

for /f "tokens=*" %%A in ('doff _yyyymmdd_hhmiss -1d') do set dt=%%A

Open in new window



***** EDIT *****

Whoops, looks like the creator of that handy freeware utility let the domain go.  You can still access the prior content of that page to see a description at the Internet Wayback Machine project via the first link below, and download the utility itself via the second link below.



Featured Post

HTML5 and CSS3 Fundamentals

Build a website from the ground up by first learning the fundamentals of HTML5 and CSS3, the two popular programming languages used to present content online. HTML deals with fonts, colors, graphics, and hyperlinks, while CSS describes how HTML elements are to be displayed.

Join & Write a Comment

Microsoft Office 365 Backup and Restore Solution by SysTools to export Office 365 mailbox to PST / EML file format on Windows OS. On Mac, tool backup O365 to PST / MBOX / MSG / EML / EMLX file formats. Not only this, restore option helps to import s…
I've published three five-minute Experts Exchange video Micro Tutorials that describe terrific features in an excellent, free PDF product called PDF-XChange Editor: How to rotate pages in a PDF with free software (https://www.experts-exchange.com…

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month