Reputation: 889
is there any way in batch script to check a format of a time?
Ex. I have a scenario with a wrong format of time:
set tm=431:00:00
I want to check it if tm is a time with a format HH:MM:SS.
if %tm% == %format% (
do something ) else (
do nothing )
Is it possible in batch script to do some checking like that?
Please spare with me. Thanks.
Upvotes: 0
Views: 370
Reputation: 3679
One easy option is to use FINDSTR /R
to do a regular expression check if the time has the right number of digits.
set tm=43:00:00
echo %tm%| findstr /R "^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$"
if errorlevel 1 (
echo Invalid time!
) else (
echo OK
)
The problem with that approach is that FINDSTR only has limited regex support, so you can't really tell with the above if the time actually makes sense (e.g. if hour is 25...)
You could improve the script by doing a few separate checks. For example: if the hour's first digit is [2] then the second digit must be [0-3]. However, for all that effort, I'd rather just call out to a simple PowerShell script to do check if the time is correct and use the output from the PS script in your batch file.
Upvotes: 1
Reputation: 67216
set origTime=%time%
echo %tm% | time > nul
if errorlevel 1 (
echo Time format is invalid
)
echo %origTime% | time > nul
EDIT New method as requested
The following code check that: - The time have 3 parts separated by colon - Each part be a number - The multiplication of the 3 numbers be not zero
for /F "tokens=1-3 delims=:" %%a in ("%tm%") do set HH=%%a& set MM=%%b& set SS=%%c
rem Set ERRORLEVEL to zero:
ver > nul
set /A result=%HH%*%MM%*%SS% > nul
if errorlevel 1 echo Bad format
if %result% == 0 echo Bad format
Previous example may give you more ideas on how check for other cases...
Upvotes: 1