THIS ARTICLE IS ORIGINAL - By HeelpBook Staff
If you want to use %DATE% in your batch DOS script in a simpler manner, for example if you want to output this information for naming your log/output files, you can use this approach:
- Output the DATE /T to a temp text file;
- Set a variable with the date stored in temp text file;
- Delete the useless temp text file; :-)
- Now clean the date variable removing dashes/dots/anything else (in this case only hyphen and slashes) and output the same variable cleaned to screen;
@ECHO OFF DATE /T > dates.txt SET /P dates= <dates.txt DEL /F /Q dates.txt ECHO %dates% FOR /F "usebackq tokens=2,3 delims=/- " %A IN ('%dates%') DO (SET dateset=%A%B) ECHO %dateset%
See the last line in this screenshot. Note that i've told to DOS to extract only month and year from DATE /T, but you could obviously set tokens=1,2,3 and SET dateset=%A%B%C to output the whole date to screen (so even the day information):
In this case %A refers to the second token extracted from the variable %dateset%, and so %B will refer to the third token (slash or hyphen delimited). So you can ask me: "...but, if i want to output the YEAR as first information and then the MONTH?"
Nothing more simple:
@ECHO OFF DATE /T > dates.txt SET /P dates= <dates.txt DEL /F /Q dates.txt ECHO %dates% FOR /F "usebackq tokens=2,3 delims=/- " %A IN ('%dates%') DO (SET dateset=%B%A) ECHO %dateset%
REMEMBER:This codes will operate only if you copy and paste it in a command prompt (XP, Vista or Seven), so if you want to use it in a batch file script, you will have to modify it in this manner:
- Replace the %A occurences with %%A;
- The same with %B to %%B;
@ECHO OFF DATE /T > dates.txt SET /P dates= <dates.txt DEL /F /Q dates.txt ECHO %dates% FOR /F "usebackq tokens=2,3 delims=/- " %%A IN ('%dates%') DO (SET dateset=%%A%%B) ECHO %dateset%
Enjoy :-)