How to get today's date in Windows batch environment?
I would like to get today's date in the format of YYYYMMDD in Windows batch environment, but don't know where to start or wha开发者_如何学编程t to do.
Any code or direction is appreciated.
On my system, where echo %date%
returns dd/mm/yyyy
:
set now=%date:~6,4%%date:~3,2%%date:~0,2%
echo.%now%
The syntax used is %date:~S,L%
where S
is a character offset and L
is the length to read from the value returned by %date%
.
You may also use a FOR command to separate the parts of a date:
for /f "tokens=1-3 delims=/" %%a in ("%date%") do set now=%%c%%a%%b
Date components are split by / (delims) and taken the first three parts (tokens) in variable %%a and successive ones (%%b and %%c).
Although this seems more complicated than the former method, it is less prone to get errors when you used it. For further details, type: FOR /?
@echo off
for /f "tokens=*" %%a in ('
"wmic path Win32_LocalTime get year,month,day /value|findstr ="
') do @set %%a
echo %year%%month%%day%
pause
Rob van Der Woude has a script that parses the date without using WMIC, which requires administrative rights. Here's the link to the script. Just rename it to a .BAT file:
http://www.robvanderwoude.com/files/sortdate_dos.txt
On my Windows 10 machine, the %date% format is different from the values expected by @Alex K. answer, so it didn't work for me. After doing some more research, I dug up the following script, which is good for obtaining any date in the format of your choice. Use day=0
for today, day=1
for tomorrow, day=-1
for yesterday, etc...
set day=0
echo >"%temp%\%~n0.vbs" s=DateAdd("d",%day%,now) : d=weekday(s)
echo>>"%temp%\%~n0.vbs" WScript.Echo year(s)^& right(100+month(s),2)^& right(100+day(s),2)
for /f %%a in ('cscript /nologo "%temp%\%~n0.vbs"') do set "result=%%a"
del "%temp%\%~n0.vbs"
set "YYYY=%result:~0,4%"
set "MM=%result:~4,2%"
set "DD=%result:~6,2%"
set "today=%yyyy%%mm%%dd%"
echo %today%
@raider33 's script works, here is another way which use PowerShell:
@echo off
for /f %%i in ('PowerShell -Command "Get-Date -uformat '%%Y%%m%%d'"') do (
set "Today=%%i"
)
echo,%Today%
精彩评论