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

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

    I have converted to using Powershell calls for this purpose in my scripts. It requires script execution permission and is by far the slowest option. However it is also localization independent, very easy to write and read, and it is much more feasible to perform adjustments to the date like addition/subtraction or get the last day of the month, etc.

    Here is how to get the day, month, and year

    for /f %%i in ('"powershell (Get-Date).ToString(\"dd\")"') do set day=%%i
    for /f %%i in ('"powershell (Get-Date).ToString(\"MM\")"') do set month=%%i
    for /f %%i in ('"powershell (Get-Date).ToString(\"yyyy\")"') do set year=%%i
    

    Or, here is yesterday's date in yyyy-MM-dd format

    for /f %%i in ('"powershell (Get-Date).AddDays(-1).ToString(\"yyyy-MM-dd\")"') do set yesterday=%%i

    Day of the week

    for /f %%d in ('"powershell (Get-Date).DayOfWeek"') do set DayOfWeek=%%d

    Current time plus 15 minutes

    for /f %%i in ('"powershell (Get-Date).AddMinutes(15).ToString(\"HH:mm\")"') do set time=%%i

提交回复
热议问题