Question:
Batch Script - Capturing and formatting the time into separate variables?
tomstevl
2008-10-13 05:41:42 UTC
Please can anyone help? I would like to capture the current time into separate variables and remove any leading zeroes.

E.g: Time=10:07:03
Into: Hour=10 Min=7 Sec=3

Is this possible?
Three answers:
Raymond B
2008-10-14 20:22:05 UTC
The previous answer is incorrect. Saving this to a batch file and running it at 9:04 AM shows this:

C:\>test

9:04:08.26

Hour= 9

Min=04

Sec=08



Instead you will want to use an if statement and a combination of the above. Here is what I use

@echo off

for /f "tokens=1,2,3 delims=:. " %%a in ("%TIME%") do (

set HOUR=%%a

set MINUTE=%%b

set SECOND=%%c

)

if {%HOUR:~0,1%}=={0} set HOUR=%HOUR:~1%

if {%MINUTE:~0,1%}=={0} set MINUTE=%MINUTE:~1%

if {%SECOND:~0,1%}=={0} set SECOND=%SECOND:~1%



echo Hour: %HOUR% Minute: %MINUTE% Second: %SECOND%
?
2014-01-20 12:30:51 UTC
@Raymond B



Mate, you're a ******* idiot. @Justin F answered almost perfectly, and you said his answer was incorrect. Your answer utilises the FOR loop, which is highly unneccessary for what the OC is asking. Choose which one is better between either 1 or 100 lines and thats how fucked ur brain is.



Justin's code:



@echo off

echo %TIME%

echo Hour=%TIME:~0,2%

echo Min=%TIME:~3,2%

echo Sec=%TIME:~6,2%



Works perfectly, however the OC wanted each to be a seperate variable, therefore the answer should be:



@echo off

set Hour=%TIME:~0,2%

set Min=%TIME:~3,2%

set Sec=%TIME:~6,2%

echo Time: %Hour%:%Min%:%Sec%



If you want to actually make a working clock, I would use the choice command. Other options inclue using timeout or ping, but both break quickly.



@echo off

:start

echo The time is: %TIME:~0,2%:%TIME:~3,2%:%TIME:~6,2%

choice /t 1 /n /m "Exit? [Y/N] /d 2

if ERRORLEVEL=2 goto start

if ERRORLEVEL=1 exit



There you go, ******* spastic cunts.
Justin F
2008-10-13 13:17:07 UTC
Hi - when you ask for 'Batch Script' I am assuming you mean a DOS .bat file.



Try this one (works in a CMD window in XP)



@echo off

echo %TIME%

echo Hour=%TIME:~0,2%

echo Min=%TIME:~3,2%

echo Sec=%TIME:~6,2%



The variable %TIME% displays the current system time, the :~ says select the start point, the comma and the next digit is the length.


This content was originally posted on Y! Answers, a Q&A website that shut down in 2021.
Loading...