If you can use powershell, why not do it with this simple one line:
powershell -Command [DateTime]::Now.ToString(\"yyyyMMdd_hhmmss\")
It is an example that outputs actual Year, Month, Day, Hour, Minute and Second.
See last part, it is the format you want, so you can get it with the format you want.
Explanation of what it does:
- With
.ToString(
...)
it formats the output of [DateTime]::Now
in the format yyyyMMdd_hhmmss
And if you want it in a bacth file you can use the trick of for /f "delims="
, see an example:
for /f "delims=" %a in ('powershell -Command [DateTime]::Now.ToString(\"yyyyMMdd_hhmmss\"^)') do @echo DateTime is: %a
If you want to use it inside a .BAT or .CMD file you must double the % as this:
for /f "delims=" %%a in ('powershell -Command [DateTime]::Now.ToString(\"yyyyMMdd_hhmmss\"^)') do @echo DateTime is: %%a
Importat note: The ^ character is t avoid for see the ) as final, same as \ does this " inside powershell, etc. It is a meta-charater that tells next character must not be interpreted.
And if you need datetime inside a variable on a batch, see this:
@ECHO OFF
for /f "delims=" %%a in ('powershell -Command [DateTime]::Now.ToString(\"yyyyMMdd_hhmmss\"^)') do @Set MyVariable=%%a
ECHO %MyVariable%
P.D.: There are side effects on using powershell, it changes CMD window size and font (and let them changed after exit), also sometimes it takes some seconds to run such simple command.