Print datetime in Windows cmd
Solution 1:
It can be done, but it's not as neat and tidy as that:
echo %date:~-4%%date:~3,2%%date:~0,2%%time:~0,2%%time:~3,2%%time:~6,2%
This for me returns:
Note this is locale specific, and it's a bit of a hack around really. It's simply a concatenation of:
- Last 4 chars of DATE
- Mid of Date, 2 chars starting from char 3
- Mid of Date, 2 chars starting from char 0
- Mid of Time, 2 chars starting from char 0
- Mid of Time, 2 chars starting from char 3
- Mid of Time, 2 chars starting from char 6
Solution 2:
I would like to have it formatted like 20160225155958
which is the output format of running:
date +"%Y%m%d%H%M%S"
on Linux.
Using %date%
to provide a solution is, as pointed out in another answer, dependent on the OS Locale, Regional, and Language settings.
Using wmic
, on the other hand, works independently of OS Locale, Language or the user's chosen date format (Control Panel/Regional).
The following batch file uses wmic
to retrieve the date and (local) time in the OP's specified format, so doesn't suffer the disadvantage of a solution using %date%
.
getdate.cmd:
@echo off
setlocal
rem use findstr to strip blank lines from wmic output
for /f "usebackq skip=1 tokens=1-6" %%g in (`wmic Path Win32_LocalTime Get Day^,Hour^,Minute^,Month^,Second^,Year ^| findstr /r /v "^$"`) do (
set _day=00%%g
set _hours=00%%h
set _minutes=00%%i
set _month=00%%j
set _seconds=00%%k
set _year=%%l
)
rem pad with leading zeros
set _month=%_month:~-2%
set _day=%_day:~-2%
set _hh=%_hours:~-2%
set _mm=%_minutes:~-2%
set _ss=%_seconds:~-2%
set _date=%_year%%_month%%_day%%_hh%%_mm%%_ss%
echo %_date%
endlocal
The above batch file is a modified version of the example in getdate
Output:
F:\test>date /t && time /t
25/02/2016
16:49
F:\test>getdate
20160225164929
F:\test>
Cywin for comparison:
DavidPostill@Hal /f/test
$ date +"%Y%m%d%H%M%S"
20160225164938
Further Reading
- An A-Z Index of the Windows CMD command line - An excellent reference for all things Windows cmd line related.
- for /f - Loop command against the results of another command.
- getdate - Display the date and time independent of OS Locale, Language or the users chosen date format (Control Panel/Regional).
- variables - Extract part of a variable (substring).
- wmic - Windows Management Instrumentation Command.