Batch script date into variable

后端 未结 8 1433
终归单人心
终归单人心 2020-12-01 22:34
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 int

相关标签:
8条回答
  • 2020-12-01 23:21

    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
     )
    
    0 讨论(0)
  • 2020-12-01 23:25

    This is what I'd use in an XP pro machine and higher. XP Home does not have wmic.

    :: timestamp YYYYMMDD_HHMMSS
    @echo off
    for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
    set dt=%dt:~0,8%_%dt:~8,6%
    echo %dt%
    pause
    

    and another

    :: timestamp YYYY-MM-DD_HH-MM-SS
    @echo off
    for /f "delims=" %%a in ('wmic OS Get localdatetime  ^| find "."') do set dt=%%a
    set dt=%dt:~0,4%-%dt:~4,2%-%dt:~6,2%_%dt:~8,2%-%dt:~10,2%-%dt:~12,2%
    echo %dt%
    pause
    
    0 讨论(0)
提交回复
热议问题