Search Tools Links Login

Grabbing System Date in a Batch File


Batch programming can be a powerful thing. Basically, anything you can run at a command prompt can be run in a batch file. Coupled with task scheduler, process automation nirvana can be achieved. However, one thing that is conspicuously is the presence of a date or time variable. For example, if you wanted to date or time encode a filename or create a log entry, you have no way to do that in native batch. But there is a way! There is a DATE command is available though. With a simple bit of trickery, we can grab that info and store it in a variable, then use it however we want within our script. The actual code is posted at the bottom of this article, but I want to give a basic flow/explanation of what is going on with it first. Because knowledge is power, that's why. And not everyone is a seasoned IT professional.

Pretty straightfoward, eh? At the bottom of the code, there is a small section on how to use the variable in some file operations, such as creating a directory or copying a file. Anyway, here is the code, watch out for line wrap. Hope this helps!

.echo off
echo *** Finding DateStamp YYYYMMDD

REM ***
REM *** Echo date to null. If the date command is not available, exit the script
REM ***

echo. | date | FIND "(mm" > NUL
If errorlevel 1,(call :Parsedate DD MM) Else,(call :Parsedate MM DD)
goto :ScriptDone

:Parsedate ----------------------------------------------------------

REM ***
REM *** The date is available. Parse the output of DATE /T
REM ***

For /F "tokens=1-4 delims=/.- " %%A in ('date /T') do if %%D!==! (set %1=%%A&set %2=%%B&set YYYY=%%C) else (set DOW=%%A&set %1=%%B&set %2=%%C&set YYYY=%%D)
(Set DateStamp=%YYYY%%MM%%DD%)

REM ***
REM *** Example usage of DateStamp variable
REM ***

echo *** Datestamp:%DateStamp%

REM ***
REM *** Sample usage of the variable
REM ***

REM *** first, create a directory with the datestamp pre-pended to the directory name

mkdir k:\backup\%DateStamp%-webroot

REM *** copy a file with the date in the filename

copy c:\myfile.txt k:\backup\%DateStamp%_myfile.txt

:ScriptDone

About this post

Posted: 2012-05-04
By: dwirch
Viewed: 1,455 times

Categories

Windows Commandline

Tutorials

Scripting

Windows

Attachments

No attachments for this post


Loading Comments ...

Comments

dwirch posted this comment on 2013-08-25:

Anyone notice the bug in the code above?

You must be logged in to make a comment.