Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Batch script date into variable

for /F "tokens=1-4 delims=/ " %%i in ('date /t') do (
set Day=%%k
set Month=%%j
set Year=%%l
set DATE=%%k/%%j/%%l)

I am try to get the date into the above variables in a batch script, but currently the date comes out as

2011/04/

Any suggestions on how to fix this?

like image 585
Jim Jeffries Avatar asked Apr 08 '11 11:04

Jim Jeffries


2 Answers

You don't get what you expected because %DATE% returns the current date using the windows settings for the "short date format". This setting is fully (endlessly) customizable.

One user may configure its system to show the short date as Fri040811; while another user (even in the same system) may choose 08/04/2011. It's a complete nightmare for a BAT programmer.

One possible solution is to use WMIC, instead. WMIC is the WMI command line interface to WMI. WMI Windows Management Instrumentation is the http://en.wikipedia.org/wiki/Windows_Management_Instrumentation

WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table

returns the date in a convenient way to directly parse it with a FOR.

Completing the parse and putting the pieces together

 FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    SET /A TODAY=%%F*10000+%%D*100+%%A
 )
like image 199
PA. Avatar answered Sep 29 '22 04:09

PA.


I have derived the shortest from the already given solutions. This works on every system (XP Pro and up):

REM ===================================================================
REM CREATE UNIQUE DATETIME STRING IN FORMAT YYYYMMDD-HHMMSS
REM ======================================================================
FOR /f %%a IN ('WMIC OS GET LocalDateTime ^| FIND "."') DO SET DTS=%%a
SET DateTime=%DTS:~0,8%-%DTS:~8,6%
REM ======================================================================

Of course you can play with the resulting string format.

like image 35
Kees Avatar answered Sep 29 '22 03:09

Kees