segfault
segfault

Reputation: 5939

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 what to do.

Any code or direction is appreciated.

Upvotes: 6

Views: 28650

Answers (6)

Tiber Wang
Tiber Wang

Reputation: 1

@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%

Upvotes: 0

raider33
raider33

Reputation: 1673

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%

Upvotes: 0

Lizz
Lizz

Reputation: 1470

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

Upvotes: 0

walid2mi
walid2mi

Reputation: 2888

@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

Upvotes: 3

Aacini
Aacini

Reputation: 67216

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 /?

Upvotes: 2

Alex K.
Alex K.

Reputation: 175766

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%.

Upvotes: 19

Related Questions