Tuesday, December 21, 2010

Windows Command-Prompt Dates

I'm sure some people will say, "Why don't you use Powershell?" or something similar, but the plain fact is I'm not a Windows user anymore.  I've been using Linux as my primary desktop for the past 8 years or so, and I'm just versed in Powershell yet.


Anyways, for my new job I was writing a Batch script and had the need to have a date in a 4 digit format (ie. not 12/20/10 but 12/20/2010).  I found that the "date" command leaves something to be desired.  Unlike on Linux where the date command lets you manipulate the date any which way you want, Windows Command-Prompt's date only allows you to modify it or display it (with a 2 digit year).  In my script I managed to massage it with (I needed hyphens, not forward slashes):


::Quick date batch format change (MM-DD-YYYY format)
::Setups %date% variable
::First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
echo off


FOR /F "TOKENS=1 DELIMS=/ " %%A IN ('DATE /T') DO SET mm=%%A
FOR /F "TOKENS=2 DELIMS=/ EOL=/ " %%A IN ('DATE /T') DO SET dd=%%A
SET /a dd=%dd%-1
FOR /F "TOKENS=3 DELIMS=/ " %%A IN ('DATE /T') DO SET yyyy=%%A


SET date=%mm%-%dd%-%yyyy%

However, this still left me with a 2 digit year.  I was scratching my head and getting frustrated until I had an epiphany.  I could simply add 2000 to result.  And thusly:


::Quick date batch format change (MM-DD-YYYY format)
::Setups %date% variable
::First parses month, day, and year into mm , dd, yyyy formats and then combines to be MMDDYYYY
echo off


FOR /F "TOKENS=1 DELIMS=/ " %%A IN ('DATE /T') DO SET mm=%%A
FOR /F "TOKENS=2 DELIMS=/ EOL=/ " %%A IN ('DATE /T') DO SET dd=%%A
SET /a dd=%dd%-1
FOR /F "TOKENS=3 DELIMS=/ " %%A IN ('DATE /T') DO SET yyyy=%%A
SET /a yyyy=%yyyy%+2000


SET date=%mm%-%dd%-%yyyy%

Voila!  I'm sure there is a better way, but it worked for me.  Leave me any tips/alternates in the comments if you feel I'm going about it all the wrong way.

I also need to figure out how to highlight code better than just small text.

EDIT:  Found some instructions here which allowed me to make the code stand out a bit better.  Not perfect, but good enough for now.

No comments:

Post a Comment