Tech Talk : Batch – Date/Time Stamp With WMICHow many of us programmers have always wanted a quick one or two liner code to get you a nicely formatted date time stamp which we wanted to use in our file naming format, log file entry tracking, etc. Well you have come to the right spot my friend.
I had a similar need… like always. So I figure to write an article to document just that so that I can share my knowledge with everyone and no one shall bear the this trivial burden that comes by so often.
I will be using a command-line scripting interface called Windows Management Instrumentation Command-line (WMIC) to help me simplifies my needs. For the benefit of all levels of readers, I am going to start off from very basic…. what is WMIC.
If you open a command prompt and enter “wmic” (without the double quote) you will get what is shown below.

Xybernetics Batch - Date/Time Stamp With WMIC

If you want the local computer date and time, type the command shown on the screen shot below.

Xybernetics Batch - Date/Time Stamp With WMIC

If you look at the output text in the command prompt (screen shot above), it is essentially date and time in the following format; YYYMMDDHHmmss.xxxxxx-xxx
Now all we need is to pipe this text, and dissect and format it to our need. Let create a “cmd” file and write some script to do that.

REM ===== Do print command to screen =====
echo off

REM ===== Get local computer date and time =====
REM ===== If localhost date and time is not found, just capture it as YYYMMDDHHmmss.xxxxxx-xxx format  =====
REM ===== If localhost date and time found, then format it to YYYY/MM/DD =====
for /F "usebackq tokens=1,2 delims==" %%i in (`wmic os get LocalDateTime /VALUE 2^>NUL`) do if '.%%i.'=='.LocalDateTime.' set dtStamp=%%j
set dtStamp=%dtStamp:~0,4%/%dtStamp:~4,2%/%dtStamp:~6,2% %dtStamp:~8,2%:%dtStamp:~10,2%:%dtStamp:~12,6%

REM ===== Output the date and time stamp =====
echo %dtStamp%

You can download this sample file from here

From here on, the world is your oyster in however way you choose to use the date and time stamp.