Link to home
Start Free TrialLog in
Avatar of rschraeger
rschraeger

asked on

Batch File Need to Format Date

I have a batch file (yes I need to use batch) that need to find the current date and display it in yyyy-mm-dd
I can get the format in yyyy mm dd. I need to insert the hypens in
My code:
FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%YYYY%-%MM%-%DD%
What this displays is
2008 -02 -16
I can't have a spaces before the hypens.
Avatar of Frosty555
Frosty555
Flag of Canada image

In Windows XP there's a dynamic environment variable called %date% that returns the current date. Your batch file is overwriting it... so you'll need to do this from a new command prompt session before your date code had been run yet

echo %date:~6,4%-%date:~3,2%-%date:~0,2%

Keep in mind though, both the DATE command and the %DATE% environment variable return the date formatted based on the current regional settings. It will only work for your particular set of regional settings. Mine were the default Canadian regional settings. I think USA uses the same date format.
Avatar of Steve Knight
BTW you can use set the command

SET thedate=%YYYY%-%MM%-%DD%
set thedate=% =%

to replace all spaces with nothing
Likewise you can do

set thedate=%/=-%
to replace / with -

but you have a solution above.  Be careful as Frosty555 says though as date formats can be differnet even between different OS's, e.g.  Thu 15/02/2008 or just 15/02/2008

Steve
Avatar of rschraeger
rschraeger

ASKER

I looked at the solution from gragon-it but that is not what i am looking for.

FOR /F "TOKENS=1* DELIMS= " %%A IN ('DATE/T') DO SET CDATE=%%B
FOR /F "TOKENS=1,2 eol=/ DELIMS=/ " %%A IN ('DATE/T') DO SET mm=%%B
FOR /F "TOKENS=1,2 DELIMS=/ eol=/" %%A IN ('echo %CDATE%') DO SET dd=%%B
FOR /F "TOKENS=2,3 DELIMS=/ " %%A IN ('echo %CDATE%') DO SET yyyy=%%B
SET date=%YYYY%-%MM%-%DD%
When I run this it will give me 2008 -02 -17  If I take the "-" out of the folowing:  =%YYYY%-%MM%-%DD%  I will get 2008 02 17  by placing the hyphen between the two %% signs I can get the hyphen in but there is also a space.  I need it to look like 2008-02-17
ASKER CERTIFIED SOLUTION
Avatar of Gastone Canali
Gastone Canali
Flag of Italy image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial