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?
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
)
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With