How do I get the day month and year from a Windows cmd.exe script?

前端 未结 14 1393
长情又很酷
长情又很酷 2020-12-23 17:02

How do I get the current day month and year from inside a Windows cmd script? I need to get each value into a separate variable.

14条回答
  •  我在风中等你
    2020-12-23 17:13

    LANGUAGE INDEPENDENCY:

    The Andrei Coscodan solution is language dependent, so a way to try to fix it is to reserve all the tags for each field: year, month and day on target languages. Consider Portugese and English, after the parsing do a final set as:

    set Year=%yy%%aa%
    set Month=%mm%
    set Day=%dd%
    

    Look for the year setting, I used both tags from English and Portuguese, it worked for me in Brazil where we have these two languages as the most common in Windows instalations. I expect this will work also for some languages with Latin origin like as French, Spanish, and so on.

    Well, the full script could be:

    @echo off
    setlocal enabledelayedexpansion
    
    :: Extract date fields - language dependent
    for /f "tokens=1-4 delims=/-. " %%i in ('date /t') do (
            set v1=%%i& set v2=%%j& set v3=%%k
            if "%%i:~0,1%%" gtr "9" (set v1=%%j& set v2=%%k& set v3=%%l)
    
            for /f "skip=1 tokens=2-4 delims=(-)" %%m in ('echo.^|date') do (
                set %%m=!v1!& set %%n=!v2!& set %%o=!v3!
        )
    )
    
    :: Final set for language independency (English and Portuguese - maybe works for Spanish and French)
    set year=%yy%%aa%
    set month=%mm%
    set day=%dd%
    
    
    :: Testing
    echo Year:[%year%] - month:[%month%] - day:[%day%]
    
    endlocal
    pause
    

    I hope this helps someone that deal with diferent languages.

提交回复
热议问题