Windows – How to get the current system date and time using a command prompt

batchcommand linewindows

I would like to get the current system date and time using a command prompt.
How do I get the date to be in a specific format, MM-DD-YYYY HH:MIN AM/PM?

Best Answer

Very easy to get the date and time, actually:

set Year=
for /f "skip=2" %%x in ('wmic Path Win32_LocalTime get Year^,Month^,Day^,Hour^,Minute^,Second /Format:List') do (
  if not defined Year set %%x
)

I'm assuming local time here. If you need UTC, adapt it accordingly.

Your format makes things more complicated. Apologies if I get something wrong here, I'm not familiar with am/pm formats.

if %Hour% LSS 12 (
  set ampm=AM
  if %Hour%==0 set Hour=12
) else (
  set ampm=PM
  set /a Hour-=12
)

We need a few leading zeroes:

if %Month% LSS 10 set Month=0%Month%
if %Day% LSS 10 set Day=0%Day%
if %Minute% LSS 10 set Minute=0%Minute%
if %Hour% LSS 10 set Hour=0%Hour%

Then it's time to assemble the parts:

set Timestamp=%Month%-%Day%-%Year% %Hour%:%Minute% %ampm%

(Just a random note: Why on earth would you want that timestamp format?)