We help IT Professionals succeed at work.

Display 24-Hour Time with CMD Command with System Changes

deharvy
deharvy asked
on
The command: for /f %a in ('time/t') do echo %a

The above command outputs the current local time. What command do I use to get an output in 24-HR time?

For example: If I run this command at 6pm, it will output '6:00pm'. I want to see '18:00' without making any system changes.

Is this possible via a batch script?
Comment
Watch Question

%TIME% will give you the 24-hour time

so use

@echo %TIME%
Steve KnightIT Consultancy
SILVER EXPERT
Commented:
Try this:

Steve

@echo off

for /f "tokens=1,2 delims=:m" %%a in ('time /t') do set hh=%%a & set mm=%%b
REM Get PM or am.  Strip a or p off if it is there.  If 24h already will be ok still
set pm=%mm:~-1,1%
if %pm%=="p" set mm=%mm:~0,-1%
if %pm%=="a" set mm=%mm:~0,-1%

Rem Add leading zeroes to hh
set /a hh=100+%hh%
set hh=%hh:~1%

Rem Add 12 hrs if pm
if "%pm%"=="p" set /a hh=%hh%+12

echo Time is %hh%:%mm%
Steve KnightIT Consultancy
SILVER EXPERT
Commented:
Haha, good point there... can't remember seeing %time% with am/pm on it so you are probably right there.  It does give hh:mm:ss.ss though so you may want to use

%time:~0,5%

or you could use the sledgehammer approach above!

Steve

Author

Commented:
Darron was correct when indicating %time%. However, %time:~0,5% was the complete solution. The long script works as well; but for me, the simplier the better. :) Thanks!

Author

Commented:
echo %time:~0,5% worked just fine for me and this flexible command allows to me many other things like only getting the hour, or minute or second. Thanks for your help!
Steve KnightIT Consultancy
SILVER EXPERT

Commented:
Glad it helped

Stee