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

前端 未结 14 1419
长情又很酷
长情又很酷 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:09

    The following batch code returns the components of the current date in a locale-independent manner and stores day, month and year in the variables CurrDay, CurrMonth and CurrYear, respectively:

    for /F "skip=1 delims=" %%F in ('
        wmic PATH Win32_LocalTime GET Day^,Month^,Year /FORMAT:TABLE
    ') do (
        for /F "tokens=1-3" %%L in ("%%F") do (
            set CurrDay=0%%L
            set CurrMonth=0%%M
            set CurrYear=%%N
        )
    )
    set CurrDay=%CurrDay:~-2%
    set CurrMonth=%CurrMonth:~-2%
    echo Current day  :  %CurrDay%
    echo Current month:  %CurrMonth%
    echo Current year :%CurrYear%
    

    There are two nested for /F loops to work around an issue with the wmic command, whose output is in unicode format; using a single loop results in additional carriage-return characters which impacts proper variable expansion.

    Since day and month may also consist of a single digit only, I prepended a leading zero 0 in the loop construct. Afterwards, the values are trimmed to always consist of two digits.

提交回复
热议问题