How do I get the day month and year from a Windows

2019-03-08 14:17发布

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.

10条回答
姐就是有狂的资本
2楼-- · 2019-03-08 15:03

This variant works for all localizations:

@echo off
FOR /F "skip=1 tokens=1-6" %%A IN ('WMIC Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year /Format:table') DO (
    if "%%B" NEQ "" (
        SET /A FDATE=%%F*10000+%%D*100+%%A
    )
)
@echo on
echo date=%FDATE%
echo year=%FDATE:~2,2%
echo month=%FDATE:~4,2%
查看更多
Melony?
3楼-- · 2019-03-08 15:07
echo %Date:~7,2% gets current day

7 is starting position 2 number of digits to display

echo %Date:~7,2% gets current day

echo %Date:~4,2% gets current month

echo %Date:~10,4% gets current year
查看更多
我命由我不由天
4楼-- · 2019-03-08 15:09

The only reliably way I know is to use VBScript to do the heavy work for you. There is no portable way of getting the current date in a usable format with a batch file alone. The following VBScript file

Wscript.Echo("set Year=" & DatePart("yyyy", Date))
Wscript.Echo("set Month=" & DatePart("m", Date))
Wscript.Echo("set Day=" & DatePart("d", Date))

and this batch snippet

for /f "delims=" %%x in ('cscript /nologo date.vbs') do %%x
echo %Year%-%Month%-%Day%

should work, though.

While you can get the current date in a batch file with either date /t or the %date% pseudo-variable, both follow the current locale in what they display. Which means you get the date in potentially any format and you have no way of parsing that.

查看更多
贪生不怕死
5楼-- · 2019-03-08 15:09
powershell Set-Date -Da (Get-Date -Y 1980 -Mon 11 -Day 17)
查看更多
登录 后发表回答