Batch Script fails in IF statement - windows

My batch script is failing in the second if state of :nbig. (I have found this out using #echo after each statement). However, the SET statement within the if succeed if run normally, as does the if statement with an #echo inside. This is very peculiar and I can't see what I have done wrong.
My code is here:
:: Set the day and night values
set /A nighttemp = 2700
set /A daytemp = 6500
:: Set Transition Duration
set /A transitionduration = 60
:: Set times in minutes from midnight
set /A tnight = 1380
set /A tday = 480
For /f "tokens=1-4 delims=/:." %%a in ("%TIME%") do (
SET /A HH24=%%a
SET /A MI=%%b
SET /A SS=%%c
SET /A FF=%%d
)
SET /A mins = %HH24%*60 + %MI%
SET /A tdaywindow = %tday% + 60
SET /A tnightwindow = %tnight% + 60
if %tnight% GEQ %tday% ( GOTO NBIG)
if %tnight% LSS %tday% ( GOTO DBIG)
pause
:NBIG
if %mins% LSS %tday% ( SET /A temp = %nighttemp% )
if %mins% LSS %tdaywindow% ( SET /A temp = (%daytemp% - %nighttemp%)*((%mins% - %tday%)/60) + %nighttemp% )
if %mins% LSS %tnight%( SET /A temp = %daytemp% )
if %mins% LSS %tnightwindow%( SET /A temp = (%nighttemp% - %daytemp%)*((%mins% - %tnight%)/60) + %daytemp% )
GOTO ENDING
:DBIG
if %mins% LSS %tnight%( SET /A temp = %daytemp% )
if %mins% LSS %tnightwindow% ( SET /A temp = (%nighttemp% - %daytemp%)*((%mins% - %tnight%)/60) + %daytemp%)
if %mins% LSS %tday% ( SET /A temp = %nighttemp% )
if %mins% LSS %tdaywindow% ( SET /A temp = (%daytemp% - %nighttemp%)*((%mins% - %tday%)/60) + %nighttemp% )
GOTO ENDING
:ENDING
#echo %temp%
pause
::%~dp0\redshift.exe -O %temp%
A correctly running program should #echo the value of temp, however it errors.
(Aside: This is to run the redshift program with custom times...)

The batch parser must parse the open and close parentheses before SET /A command, so a closing paren within SET /A is being applied to the opening paren before SET /A.
You would either need to escape the closing parens within the computation
if %mins% LSS %tdaywindow% ( SET /A temp = (%daytemp% - %nighttemp%^)*((%mins% - %tday%^)/60^) + %nighttemp% )
or better yet, enclose the entire assignment within quotes:
if %mins% LSS %tdaywindow% ( SET /A "temp = (%daytemp% - %nighttemp%)*((%mins% - %tday%)/60) + %nighttemp%" )
But perhaps the simplest solution is to ditch the outer parens entirely - they are not needed with the way you have structured your code.
if %mins% LSS %tdaywindow% SET /A "temp = (%daytemp% - %nighttemp%)*((%mins% - %tday%)/60) + %nighttemp%"
Even though they are not needed with this last form, I still like to enclose my SET assignment within quotes.
Unrelated to your error, you can further simplify your code by using the SET /A feature that automatically expands numeric variables without needing % or ! (only available to SET /A)
if %mins% LSS %tdaywindow% SET /A "temp = (daytemp - nighttemp)*((mins - tday)/60) + nighttemp"

Related

Compare array of numbers in a batch script

I'm trying to compare a sequence of 9 numbers (separated by ,) using a batch file.
The comparison is always made by the corresponding sequence like:
mPrevious[0] <-> mCurrent[0]
mPrevious[1] <-> mCurrent[1]
I need to know if at least one sequece have changed. In the example bellow, 234 changed to 230 and 146 to 149.
The sketch I have so far is:
setlocal ENABLEDELAYEDEXPANSION
#echo off
set mPrevious=229,234,235,127,58,0,131,133,146
set mCurrent=229,230,235,127,58,0,131,133,149
for /f "tokens=1,2,3,4,5,6,7,8,9 delims=," %%a IN ('echo !mPrevious!') do (
)
The number of entries (currently 9) might change in the future. But for now they are just 9.
I'm not sure what is the proper way to do it inside a batch script.
#echo off
title <nul && title ...\%~nx0
setlocal enabledelayedexpansion
set "_mPrevious=229,234,235,127,58,0,131,133,146"
set "_mCurrents=229,230,235,127,58,0,131,133,149"
echo/!_mPrevious!|find "!_mCurrents!" >nul && (
endlocal & echo\Nothing changed^!! & goto :EOF )
for %%i in (!_mPrevious!)do set /a "_i+=1+0" && call set "_mPrev_!_i!=%%~i"
for %%j in (!_mCurrents!)do set /a "_j+=1+0" && call set "_mCurr_!_j!=%%~j"
if !_i! neq !_j! endlocal & echo\Varyables have different lengths^!! & goto :EOF
for /L %%L in (1 1 !_j!)do if !_mPrev_%%~L! neq !_mCurr_%%~L! echo\!_mPrev_%%~L! updated to: !_mCurr_%%~L!
endlocal && goto :EOF
Outputs:
234 updated to: 230
146 updated to: 149
One simple way to do this only if necessary and only if both variable has same length:
Make a first comparison if the variables are the same, there was a change in the values:
echo/!_mPrevious!|find "!_mCurrents!" >nul && (
endlocal & echo\Nothing changed^!! & goto :EOF )
And a second if they continue with the same length:
if !_i! neq !_j! endlocal & echo\Variables have different lengths^!! & goto :EOF
Obs.: 1. I prefer replace [ ] to one simple _
Obs.: 2. Also, change i+= to _i+=1+0, where no need predefined set command: set i=0
The FOR token delimiters are: <SPACE> <TAB> <NBSP> , ; =
Therefore, you can put it into a FOR loop, but it would fail if the content contained * or ?.
#echo off
====SETLOCAL EnableDelayedExpansion EnableExtensions
set/a"#=cnt=0"
::Define lists
set "mPrevious=229,234,235,127,58,0,131,133,146"
set "mCurrent=229,230,235,127,58,0,131,133,149"
FOR %%P in (!mPrevious!) do (
FOR %%C in (!mCurrent!) do (
if !cnt! equ !#! echo(%%P %%C
set/a"cnt+=1"
)
set/a"cnt=0,#+=1"
)
This is an approach using some self-expanding code:
#echo off
setlocal EnableDelayedExpansion
rem // Define constants here:
set "mPrevious=229,234,235,127,58,0,131,133,146"
set "mCurrents=229,230,235,127,58,0,131,133,149"
rem // Initialise auxiliary variables and indexes:
set "nPrevious=,%mPrevious%" & set /A "i=0"
set "nCurrents=,%mCurrents%" & set /A "j=0"
rem // Convert lists to arrays using self-expanding code:
set "_=%nPrevious:,=" & set /A "i+=1" & set "nPrevious[!i!]=%"
set "_=%nCurrents:,=" & set /A "j+=1" & set "nCurrents[!j!]=%"
rem // Verify availability of arrays:
> nul 2>&1 set nPrevious[ || set /A "i=0"
> nul 2>&1 set nCurrents[ || set /A "j=0"
rem // Determine minimal and maximal count:
if %j% gtr %i% (set /A "k=i, l=j" & set "_=#") else (set /A "k=j, l=i" & set "_=")
rem // Compare corresponding elements:
for /L %%K in (1,1,%k%) do if !nPrevious[%%K]! neq !nCurrents[%%K]! (
echo [%%K]: !nPrevious[%%K]! -^> !nCurrents[%%K]!
)
rem // Return removed or added elements:
set /A "k+=1" & for /L %%K in (!k!,1,%l%) do if defined _ (
echo [%%K]: --- -^> !nCurrents[%%K]!
) else (
echo [%%K]: !nPrevious[%%K]! -^> ---
)
endlocal
Sample output, relying on the data of the question:
[2]: 234 -> 230
[9]: 146 -> 149

Counter Conversion from Windows to Nix Environment

Presently we are using this Batch Script Counter into the Windows Environment, but we need to convert the same one into a Shell Script for Nix Environment.
What are the things need to be Change ?
setlocal enabledelayedexpansion
set /a n=0
set /a m=0
set /a nline=1
set /a mod=0
for /f %%i in (C:\VariableList\Variable.txt -> /home/Variable/AvailableList) do (
set /a n=m+1
set /a m=n
set /a mod=m%%%nline%
if !mod! EQU 0 (
run -n -D %%I
if !ERRORLEVEL! NEQ 0 (
goto end
)
)
)
:end
endlocal

manipulate string with a batch

I've got a string named "code" and an int named "lenght" which is the lenght of "code"
also int "todo" which has a value of 0,1 or 2.
0 should delete a character at position "lenght".
1 should change the caracter at position "lenght" to a random character.
2 should add a random charachter at position "lenght".
how do i archive this goal?
SET code="%*f0"
set length=0
:loop0
if defined # (
set #=%#:~1%
set /A length += 1
goto loop0
)
SET /A location=%RANDOM% * %lenght% / 32768 + 1
SET /A todo=%RANDOM% * 2 / 32768 + 1
IF %todo% == 0(
)
IF %todo% == 1(
)
IF %todo% == 2(
)
If correctly understood you, then:
#echo off
setlocal enabledelayedexpansion
set "str=%~f0"
set "len=0"
set "buf=%str%"
:loop
if defined buf (set buf=%buf:~1%& set /a "len+=1" & goto:loop)
echo Delete char at %%len%% position^:
set /a "len-=1"
echo !str:~0,%len%!
echo.
echo Change char at %%len%% position for random^:
rem set chars string
set "map=abcdefghijklmnopqrstuvwxyz"
rem convert it to array
set "i=0"
for /l %%i in (0, 1, 25) do (
for /l %%j in (1, 1, 1) do (
set "arr.!i!=!map:~%%i,%%j!" & set /a "i+=1"
)
)
rem random set 0..25
set /a "rnd=0+25*%random%/32768"
echo !str:~0,%len%!!arr.%rnd%!
endlocal
exit /b

how to get yesterday's date in a batch file

I know how to get today's date in Windows 7. here is the command that I am using:
%DATE:~6,4%%DATE:~3,2%%DATE:~0,2%
But I want to get yesterday, I do not know how.
If you're limited to just cmd.exe, then the other solutions, despite their size, are probably as good as you'll get. However, modern Windows (such as your Win7) ships with quite a few other tools which can do the job far easier.
Just create a VBScript yester.vbs script as follows:
d = date() - 1
wscript.echo year(d) * 10000 + month(d) * 100 + day(d)
Then you can call it from your cmd script with:
for /f %%a in ('cscript //nologo yester.vbs') do set yesterday=%%a
and the yesterday variable will be created in the form yyyymmdd for you to manipulate however you desire.
Found a script that will work to ensure you get the previous day even if the year or month changes Dos Yesterday Batch.
#echo off
set yyyy=
set $tok=1-3
for /f "tokens=1 delims=.:/-, " %%u in ('date /t') do set $d1=%%u
if "%$d1:~0,1%" GTR "9" set $tok=2-4
for /f "tokens=%$tok% delims=.:/-, " %%u in ('date /t') do (
for /f "skip=1 tokens=2-4 delims=/-,()." %%x in ('echo.^|date') do (
set %%x=%%u
set %%y=%%v
set %%z=%%w
set $d1=
set $tok=))
if "%yyyy%"=="" set yyyy=%yy%
if /I %yyyy% LSS 100 set /A yyyy=2000 + 1%yyyy% - 100
set CurDate=%mm%/%dd%/%yyyy%
set dayCnt=%1
if "%dayCnt%"=="" set dayCnt=1
REM Substract your days here
set /A dd=1%dd% - 100 - %dayCnt%
set /A mm=1%mm% - 100
:CHKDAY
if /I %dd% GTR 0 goto DONE
set /A mm=%mm% - 1
if /I %mm% GTR 0 goto ADJUSTDAY
set /A mm=12
set /A yyyy=%yyyy% - 1
:ADJUSTDAY
if %mm%==1 goto SET31
if %mm%==2 goto LEAPCHK
if %mm%==3 goto SET31
if %mm%==4 goto SET30
if %mm%==5 goto SET31
if %mm%==6 goto SET30
if %mm%==7 goto SET31
if %mm%==8 goto SET31
if %mm%==9 goto SET30
if %mm%==10 goto SET31
if %mm%==11 goto SET30
REM ** Month 12 falls through
:SET31
set /A dd=31 + %dd%
goto CHKDAY
:SET30
set /A dd=30 + %dd%
goto CHKDAY
:LEAPCHK
set /A tt=%yyyy% %% 4
if not %tt%==0 goto SET28
set /A tt=%yyyy% %% 100
if not %tt%==0 goto SET29
set /A tt=%yyyy% %% 400
if %tt%==0 goto SET29
:SET28
set /A dd=28 + %dd%
goto CHKDAY
:SET29
set /A dd=29 + %dd%
goto CHKDAY
:DONE
if /I %mm% LSS 10 set mm=0%mm%
if /I %dd% LSS 10 set dd=0%dd%
REM Set IIS and AWS date variables
set IISDT=%yyyy:~2,2%%mm%%dd%
set AWSDT=%yyyy%-%mm%-%dd%
#echo off
:: Strip the day of the week from the current date
FOR %%A IN (%Date%) DO SET Today=%%A
:: Parse the date, prefix day and month with an extra leading zero
FOR /F "tokens=1-3 delims=/" %%A IN ("%Today%") DO (
SET Day=0%%A
SET Month=0%%B
SET Year=%%C
)
:: Remove excess leading zeroes
SET Day=%Day:~-2%
SET Month=%Month:~-2%
:: Display the results
SET Day
SET Month
SET Year
:: Convert to Julian date
CALL :JDate %Year% %Month% %Day%
:: Display the result
SET JDate
:: Subtract 1 day
SET /A JPast = JDate - 1
:: Display the result
SET JPast
:: Convert back to "normal" date again
CALL :GDate %JPast%
:: Display the result
::SET GDate=20130121
SET GDate
echo The previous day in form YYYYMMDD is %GDate%
pause
::::::::::::::::::::::::::::::::::::::::::::::::::::::
GOTO:EOF
:JDate
:: Convert date to Julian
:: Arguments : YYYY MM DD
:: Returns : Julian date
::
:: First strip leading zeroes
SET MM=%2
SET DD=%3
IF %MM:~0,1% EQU 0 SET MM=%MM:~1%
IF %DD:~0,1% EQU 0 SET DD=%DD:~1%
::
:: Algorithm based on Fliegel-Van Flandern
:: algorithm from the Astronomical Almanac,
:: provided by Doctor Fenton on the Math Forum
:: (http://mathforum.org/library/drmath/view/51907.html),
:: and converted to batch code by Ron Bakowski.
SET /A Month1 = ( %MM% - 14 ) / 12
SET /A Year1 = %1 + 4800
SET /A JDate = 1461 * ( %Year1% + %Month1% ) / 4 + 367 * ( %MM% - 2 -12 * % Month1% ) / 12 - ( 3 * ( ( %Year1% + %Month1% + 100 ) / 100 ) ) / 4 + %DD% - 32075
SET Month1=
SET Year1=
GOTO:EOF
:GDate
:: Convert Julian date back to "normal" Gregorian date
:: Argument : Julian date
:: Returns : YYYY MM DD
::
:: Algorithm based on Fliegel-Van Flandern
:: algorithm from the Astronomical Almanac,
:: provided by Doctor Fenton on the Math Forum
:: (http://mathforum.org/library/drmath/view/51907.html),
:: and converted to batch code by Ron Bakowski.
::
SET /A P = %1 + 68569
SET /A Q = 4 * %P% / 146097
SET /A R = %P% - ( 146097 * %Q% +3 ) / 4
SET /A S = 4000 * ( %R% + 1 ) / 1461001
SET /A T = %R% - 1461 * %S% / 4 + 31
SET /A U = 80 * %T% / 2447
SET /A V = %U% / 11
SET /A GYear = 100 * ( %Q% - 49 ) + %S% + %V%
SET /A GMonth = %U% + 2 - 12 * %V%
SET /A GDay = %T% - 2447 * %U% / 80
:: Clean up the mess
FOR %%A IN (P Q R S T U V) DO SET %%A=
:: Add leading zeroes
IF 1%GMonth% LSS 20 SET GMonth=0%GMonth%
IF 1%GDay% LSS 20 SET GDay=0%GDay%
:: Return value
:: Here you can define the form that you want
SET GDate=%GYear%%GMonth%%GDay%
GOTO:EOF
Here's a solution that creates the earlierday.vbs file on the fly, uses it and deletes it afterwards.
It stores the result in the NewDate variable
This example calculates 1 day ago, but can easily calculate a date further back by changing the value of the Offset variable.
#echo off
set Offset=1
echo d = date() - WScript.Arguments.Item(0) > earlierday.vbs
echo wscript.echo year(d) * 10000 + month(d) * 100 + day(d) >> earlierday.vbs
for /f %%a in ('cscript //nologo earlierday.vbs %Offset%') do set NewDate=%%a
del earlierday.vbs
echo %NewDate%
pause
You could refine this slightly by using %temp%\earlierday.vbs to create the file in the user's temp folder.
Credits to paxdiablo as this is a simple tweak on his earlier post.
EDIT: Here's something with a loop, close to what I actually need it to do. This will take 14 days off today's date and return that date. Then it will keep going back 7 days at a time until it gets to 35 days day ago.
#echo off
SETLOCAL EnableDelayedExpansion
set BackDaysFrom=14
Set BackDaysTo=35
Set BackDaysStep=7
echo d = date() - WScript.Arguments.Item(0) > earlierday.vbs
echo wscript.echo year(d) * 10000 + month(d) * 100 + day(d) >> earlierday.vbs
for /L %%i in (%BackDaysFrom%, %BackDaysStep%, %BackDaysTo%) do (
for /f %%a in ('cscript //nologo earlierday.vbs %%i') do set NewDate=%%a
echo !NewDate!
)
del earlierday.vbs
pause

Calculate time difference in Windows batch file

How can I get the difference between two times in a Batch file? Because I want to print it in an HTML file.
I thought this would be possible, but it isn't.
Set "tijd=%time%"
echo %tijd%
echo %time%-%tijd%
Results:
11:07:48,85
11:16:58,99-11:07:48,85
But what I want is:
00:09:10,14
Or 9 minutes and 10 seconds or 550 seconds
#echo off
rem Get start time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Any process here...
rem Get end time:
for /F "tokens=1-4 delims=:.," %%a in ("%time%") do (
set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Get elapsed time:
set /A elapsed=end-start
rem Show elapsed time:
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
echo %hh%:%mm%:%ss%,%cc%
EDIT 2017-05-09: Shorter method added
I developed a shorter method to get the same result, so I couldn't resist to post it here. The two for commands used to separate time parts and the three if commands used to insert leading zeros in the result are replaced by two long arithmetic expressions, that could even be combined into a single longer line.
The method consists in directly convert a variable with a time in "HH:MM:SS.CC" format into the formula needed to convert the time to centiseconds, accordingly to the mapping scheme given below:
HH : MM : SS . CC
(((10 HH %%100)*60+1 MM %%100)*60+1 SS %%100)*100+1 CC %%100
That is, insert (((10 at beginning, replace the colons by %%100)*60+1, replace the point by %%100)*100+1 and insert %%100 at end; finally, evaluate the resulting string as an arithmetic expression. In the time variable there are two different substrings that needs to be replaced, so the conversion must be completed in two lines. To get an elapsed time, use (endTime)-(startTime) expression and replace both time strings in the same line.
EDIT 2017/06/14: Locale independent adjustment added
EDIT 2020/06/05: Pass-over-midnight adjustment added
#echo off
setlocal EnableDelayedExpansion
set "startTime=%time: =0%"
set /P "=Any process here..."
set "endTime=%time: =0%"
rem Get elapsed time:
set "end=!endTime:%time:~8,1%=%%100)*100+1!" & set "start=!startTime:%time:~8,1%=%%100)*100+1!"
set /A "elap=((((10!end:%time:~2,1%=%%100)*60+1!%%100)-((((10!start:%time:~2,1%=%%100)*60+1!%%100), elap-=(elap>>31)*24*60*60*100"
rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"
echo Start: %startTime%
echo End: %endTime%
echo Elapsed: %hh:~1%%time:~2,1%%mm:~1%%time:~2,1%%ss:~1%%time:~8,1%%cc:~1%
You may review a detailed explanation of this method at this answer.
As answered here:
How can I use a Windows batch file to measure the performance of console application?
Below batch "program" should do what you want. Please note that it outputs the data in centiseconds instead of milliseconds. The precision of the used commands is only centiseconds.
Here is an example output:
STARTTIME: 13:42:52,25
ENDTIME: 13:42:56,51
STARTTIME: 4937225 centiseconds
ENDTIME: 4937651 centiseconds
DURATION: 426 in centiseconds
00:00:04,26
Here is the batch script:
#echo off
setlocal
rem The format of %TIME% is HH:MM:SS,CS for example 23:59:59,99
set STARTTIME=%TIME%
rem here begins the command you want to measure
dir /s > nul
rem here ends the command you want to measure
set ENDTIME=%TIME%
rem output as time
echo STARTTIME: %STARTTIME%
echo ENDTIME: %ENDTIME%
rem convert STARTTIME and ENDTIME to centiseconds
set /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
set /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
rem calculating the duratyion is easy
set /A DURATION=%ENDTIME%-%STARTTIME%
rem we might have measured the time inbetween days
if %ENDTIME% LSS %STARTTIME% set set /A DURATION=%STARTTIME%-%ENDTIME%
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A DURATIONH=%DURATION% / 360000
set /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
set /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
set /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
rem some formatting
if %DURATIONH% LSS 10 set DURATIONH=0%DURATIONH%
if %DURATIONM% LSS 10 set DURATIONM=0%DURATIONM%
if %DURATIONS% LSS 10 set DURATIONS=0%DURATIONS%
if %DURATIONHS% LSS 10 set DURATIONHS=0%DURATIONHS%
rem outputing
echo STARTTIME: %STARTTIME% centiseconds
echo ENDTIME: %ENDTIME% centiseconds
echo DURATION: %DURATION% in centiseconds
echo %DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
endlocal
goto :EOF
A re-hash of Aacini's code because most likely you are going to set the start time as a variable and want to save that data for output:
#echo off
rem ****************** MAIN CODE SECTION
set STARTTIME=%TIME%
rem Your code goes here (remove the ping line)
ping -n 4 -w 1 127.0.0.1 >NUL
set ENDTIME=%TIME%
rem ****************** END MAIN CODE SECTION
rem Change formatting for the start and end times
for /F "tokens=1-4 delims=:.," %%a in ("%STARTTIME%") do (
set /A "start=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
for /F "tokens=1-4 delims=:.," %%a in ("%ENDTIME%") do (
IF %ENDTIME% GTR %STARTTIME% set /A "end=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
IF %ENDTIME% LSS %STARTTIME% set /A "end=((((%%a+24)*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
rem Calculate the elapsed time by subtracting values
set /A elapsed=end-start
rem Format the results for output
set /A hh=elapsed/(60*60*100), rest=elapsed%%(60*60*100), mm=rest/(60*100), rest%%=60*100, ss=rest/100, cc=rest%%100
if %hh% lss 10 set hh=0%hh%
if %mm% lss 10 set mm=0%mm%
if %ss% lss 10 set ss=0%ss%
if %cc% lss 10 set cc=0%cc%
set DURATION=%hh%:%mm%:%ss%,%cc%
echo Start : %STARTTIME%
echo Finish : %ENDTIME%
echo ---------------
echo Duration : %DURATION%
Output:
Start : 11:02:45.92
Finish : 11:02:48.98
---------------
Duration : 00:00:03,06
If you do not mind using powershell within batch script:
#echo off
set start_date=%date% %time%
:: Simulate some type of processing using ping
ping 127.0.0.1
set end_date=%date% %time%
powershell -command "&{$start_date1 = [datetime]::parse('%start_date%'); $end_date1 = [datetime]::parse('%date% %time%'); echo (-join('Duration in seconds: ', ($end_date1 - $start_date1).TotalSeconds)); }"
Aacini's latest code showcases an awesome variable substitution method.
It's a shame it's not Regional format proof - it fails on so many levels.
Here's a short fix that keeps the substitution+math method intact:
#echo off
setlocal EnableDelayedExpansion
set "startTime=%time: =0%" & rem AveYo: fix single digit hour
set /P "=Any process here..."
set "endTime=%time: =0%" & rem AveYo: fix single digit hour
rem Aveyo: Regional format fix with just one aditional line
for /f "tokens=1-3 delims=0123456789" %%i in ("%endTime%") do set "COLON=%%i" & set "DOT=%%k"
rem Get elapsed time:
set "end=!endTime:%DOT%=%%100)*100+1!" & set "start=!startTime:%DOT%=%%100)*100+1!"
set /A "elap=((((10!end:%COLON%=%%100)*60+1!%%100)-((((10!start:%COLON%=%%100)*60+1!%%100)"
rem Aveyo: Fix 24 hours
set /A "elap=!elap:-=8640000-!"
rem Convert elapsed time to HH:MM:SS:CC format:
set /A "cc=elap%%100+100,elap/=100,ss=elap%%60+100,elap/=60,mm=elap%%60+100,hh=elap/60+100"
echo Start: %startTime%
echo End: %endTime%
echo Elapsed: %hh:~1%%COLON%%mm:~1%%COLON%%ss:~1%%DOT%%cc:~1% & rem AveYo: display as regional
pause
*
"Lean and Mean" TIMER with Regional format, 24h and mixed input support
Adapting Aacini's substitution method body, no IF's, just one FOR (my regional fix)
1: File timer.bat placed somewhere in %PATH% or the current dir
#echo off & rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!" & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof
Usage:
timer & echo start_cmds & timeout /t 3 & echo end_cmds & timer
timer & timer "23:23:23,00"
timer "23:23:23,00" & timer
timer "13.23.23,00" & timer "03:03:03.00"
timer & timer "0:00:00.00" no & cmd /v:on /c echo until midnight=!timer_end!
Input can now be mixed, for those unlikely, but possible time format changes during execution
2: Function :timer bundled with the batch script (sample usage below):
#echo off
set "TIMER=call :timer" & rem short macro
echo.
echo EXAMPLE:
call :timer
timeout /t 3 >nul & rem Any process here..
call :timer
echo.
echo SHORT MACRO:
%TIMER% & timeout /t 1 & %TIMER%
echo.
echo TEST INPUT:
set "start=22:04:04.58"
set "end=04.22.44,22"
echo %start% ~ start & echo %end% ~ end
call :timer "%start%"
call :timer "%end%"
echo.
%TIMER% & %TIMER% "00:00:00.00" no
echo UNTIL MIDNIGHT: %timer_end%
echo.
pause
exit /b
:: to test it, copy-paste both above and below code sections
rem :AveYo: compact timer function with Regional format, 24-hours and mixed input support
:timer Usage " call :timer [input - optional] [no - optional]" :i Result printed on second call, saved to timer_end
if not defined timer_set (if not "%~1"=="" (call set "timer_set=%~1") else set "timer_set=%TIME: =0%") & goto :eof
(if not "%~1"=="" (call set "timer_end=%~1") else set "timer_end=%TIME: =0%") & setlocal EnableDelayedExpansion
for /f "tokens=1-6 delims=0123456789" %%i in ("%timer_end%%timer_set%") do (set CE=%%i&set DE=%%k&set CS=%%l&set DS=%%n)
set "TE=!timer_end:%DE%=%%100)*100+1!" & set "TS=!timer_set:%DS%=%%100)*100+1!"
set/A "T=((((10!TE:%CE%=%%100)*60+1!%%100)-((((10!TS:%CS%=%%100)*60+1!%%100)" & set/A "T=!T:-=8640000-!"
set/A "cc=T%%100+100,T/=100,ss=T%%60+100,T/=60,mm=T%%60+100,hh=T/60+100"
set "value=!hh:~1!%CE%!mm:~1!%CE%!ss:~1!%DE%!cc:~1!" & if "%~2"=="" echo/!value!
endlocal & set "timer_end=%value%" & set "timer_set=" & goto :eof
Based on previous answers, here are reusable "procedures" and a usage example for calculating the elapsed time:
#echo off
setlocal
set starttime=%TIME%
echo Start Time: %starttime%
REM ---------------------------------------------
REM --- PUT THE CODE YOU WANT TO MEASURE HERE ---
REM ---------------------------------------------
set endtime=%TIME%
echo End Time: %endtime%
call :elapsed_time %starttime% %endtime% duration
echo Duration: %duration%
endlocal
echo on & goto :eof
REM --- HELPER PROCEDURES ---
:time_to_centiseconds
:: %~1 - time
:: %~2 - centiseconds output variable
setlocal
set _time=%~1
for /F "tokens=1-4 delims=:.," %%a in ("%_time%") do (
set /A "_result=(((%%a*60)+1%%b %% 100)*60+1%%c %% 100)*100+1%%d %% 100"
)
endlocal & set %~2=%_result%
goto :eof
:centiseconds_to_time
:: %~1 - centiseconds
:: %~2 - time output variable
setlocal
set _centiseconds=%~1
rem now break the centiseconds down to hors, minutes, seconds and the remaining centiseconds
set /A _h=%_centiseconds% / 360000
set /A _m=(%_centiseconds% - %_h%*360000) / 6000
set /A _s=(%_centiseconds% - %_h%*360000 - %_m%*6000) / 100
set /A _hs=(%_centiseconds% - %_h%*360000 - %_m%*6000 - %_s%*100)
rem some formatting
if %_h% LSS 10 set _h=0%_h%
if %_m% LSS 10 set _m=0%_m%
if %_s% LSS 10 set _s=0%_s%
if %_hs% LSS 10 set _hs=0%_hs%
set _result=%_h%:%_m%:%_s%.%_hs%
endlocal & set %~2=%_result%
goto :eof
:elapsed_time
:: %~1 - time1 - start time
:: %~2 - time2 - end time
:: %~3 - elapsed time output
setlocal
set _time1=%~1
set _time2=%~2
call :time_to_centiseconds %_time1% _centi1
call :time_to_centiseconds %_time2% _centi2
set /A _duration=%_centi2%-%_centi1%
call :centiseconds_to_time %_duration% _result
endlocal & set %~3=%_result%
goto :eof
Fixed Gynnad's leading 0 Issue. I fixed it with the two Lines
SET STARTTIME=%STARTTIME: =0%
SET ENDTIME=%ENDTIME: =0%
Full Script ( CalculateTime.cmd ):
#ECHO OFF
:: F U N C T I O N S
:__START_TIME_MEASURE
SET STARTTIME=%TIME%
SET STARTTIME=%STARTTIME: =0%
EXIT /B 0
:__STOP_TIME_MEASURE
SET ENDTIME=%TIME%
SET ENDTIME=%ENDTIME: =0%
SET /A STARTTIME=(1%STARTTIME:~0,2%-100)*360000 + (1%STARTTIME:~3,2%-100)*6000 + (1%STARTTIME:~6,2%-100)*100 + (1%STARTTIME:~9,2%-100)
SET /A ENDTIME=(1%ENDTIME:~0,2%-100)*360000 + (1%ENDTIME:~3,2%-100)*6000 + (1%ENDTIME:~6,2%-100)*100 + (1%ENDTIME:~9,2%-100)
SET /A DURATION=%ENDTIME%-%STARTTIME%
IF %DURATION% == 0 SET TIMEDIFF=00:00:00,00 && EXIT /B 0
IF %ENDTIME% LSS %STARTTIME% SET /A DURATION=%STARTTIME%-%ENDTIME%
SET /A DURATIONH=%DURATION% / 360000
SET /A DURATIONM=(%DURATION% - %DURATIONH%*360000) / 6000
SET /A DURATIONS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000) / 100
SET /A DURATIONHS=(%DURATION% - %DURATIONH%*360000 - %DURATIONM%*6000 - %DURATIONS%*100)
IF %DURATIONH% LSS 10 SET DURATIONH=0%DURATIONH%
IF %DURATIONM% LSS 10 SET DURATIONM=0%DURATIONM%
IF %DURATIONS% LSS 10 SET DURATIONS=0%DURATIONS%
IF %DURATIONHS% LSS 10 SET DURATIONHS=0%DURATIONHS%
SET TIMEDIFF=%DURATIONH%:%DURATIONM%:%DURATIONS%,%DURATIONHS%
EXIT /B 0
:: U S A G E
:: Start Measuring
CALL :__START_TIME_MEASURE
:: Print Message on Screen without Linefeed
ECHO|SET /P=Execute Job...
:: Some Time pending Jobs here
:: '> NUL 2>&1' Dont show any Messages or Errors on Screen
MyJob.exe > NUL 2>&1
:: Stop Measuring
CALL :__STOP_TIME_MEASURE
:: Finish the Message 'Execute Job...' and print measured Time
ECHO [Done] (%TIMEDIFF%)
:: Possible Result
:: Execute Job... [Done] (00:02:12,31)
:: Between 'Execute Job... ' and '[Done] (00:02:12,31)' the Job will be executed
Here is my attempt to measure time difference in batch.
It respects the regional format of %TIME% without taking any assumptions on type of characters for time and decimal separators.
The code is commented but I will also describe it here.
It is flexible so it can also be used to normalize non-standard time values as well
The main function :timediff
:: timediff
:: Input and output format is the same format as %TIME%
:: If EndTime is less than StartTime then:
:: EndTime will be treated as a time in the next day
:: in that case, function measures time difference between a maximum distance of 24 hours minus 1 centisecond
:: time elements can have values greater than their standard maximum value ex: 12:247:853.5214
:: provided than the total represented time does not exceed 24*360000 centiseconds
:: otherwise the result will not be meaningful.
:: If EndTime is greater than or equals to StartTime then:
:: No formal limitation applies to the value of elements,
:: except that total represented time can not exceed 2147483647 centiseconds.
:timediff <outDiff> <inStartTime> <inEndTime>
(
setlocal EnableDelayedExpansion
set "Input=!%~2! !%~3!"
for /F "tokens=1,3 delims=0123456789 " %%A in ("!Input!") do set "time.delims=%%A%%B "
)
for /F "tokens=1-8 delims=%time.delims%" %%a in ("%Input%") do (
for %%A in ("#h1=%%a" "#m1=%%b" "#s1=%%c" "#c1=%%d" "#h2=%%e" "#m2=%%f" "#s2=%%g" "#c2=%%h") do (
for /F "tokens=1,2 delims==" %%A in ("%%~A") do (
for /F "tokens=* delims=0" %%B in ("%%B") do set "%%A=%%B"
)
)
set /a "#d=(#h2-#h1)*360000+(#m2-#m1)*6000+(#s2-#s1)*100+(#c2-#c1), #sign=(#d>>31)&1, #d+=(#sign*24*360000), #h=(#d/360000), #d%%=360000, #m=#d/6000, #d%%=6000, #s=#d/100, #c=#d%%100"
)
(
if %#h% LEQ 9 set "#h=0%#h%"
if %#m% LEQ 9 set "#m=0%#m%"
if %#s% LEQ 9 set "#s=0%#s%"
if %#c% LEQ 9 set "#c=0%#c%"
)
(
endlocal
set "%~1=%#h%%time.delims:~0,1%%#m%%time.delims:~0,1%%#s%%time.delims:~1,1%%#c%"
exit /b
)
Example:
#echo off
setlocal EnableExtensions
set "TIME="
set "Start=%TIME%"
REM Do some stuff here...
set "End=%TIME%"
call :timediff Elapsed Start End
echo Elapsed Time: %Elapsed%
pause
exit /b
:: put the :timediff function here
Explanation of the :timediff function:
function prototype :timediff <outDiff> <inStartTime> <inEndTime>
Input and output format is the same format as %TIME%
It takes 3 parameters from left to right:
Param1: Name of the environment variable to save the result to.
Param2: Name of the environment variable to be passed to the function containing StartTime string
Param3: Name of the environment variable to be passed to the function containing EndTime string
If EndTime is less than StartTime then:EndTime will be treated as a time in the next day
in that case, the function measures time difference between a maximum distance of 24 hours minus 1 centisecond
time elements can have values greater than their standard maximum value ex: 12:247:853.5214
provided than the total represented time does not exceed 24*360000 centiseconds or (24:00:00.00) otherwise the result will not be meaningful.
If EndTime is greater than or equals to StartTime then:
No formal limitation applies to the value of elements,
except that total represented time can not exceed 2147483647 centiseconds.
More examples with literal and non-standard time values
Literal example with EndTime less than StartTime:
#echo off
setlocal EnableExtensions
set "start=23:57:33,12"
set "end=00:02:19,41"
call :timediff dif start end
echo Start Time: %start%
echo End Time: %end%
echo,
echo Difference: %dif%
echo,
pause
exit /b
:: put the :timediff function here
Output:
Start Time: 23:57:33,12
End Time: 00:02:19,41
Difference: 00:04:46,29
Normalize non-standard time:
#echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=27:2457:433.85935"
call :timediff normalized start end
echo,
echo %end% is equivalent to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
Output:
27:2457:433.85935 is equivalent to 68:18:32.35
Last bonus example:
#echo off
setlocal EnableExtensions
set "start=00:00:00.00"
set "end=00:00:00.2147483647"
call :timediff normalized start end
echo,
echo 2147483647 centiseconds equals to %normalized%
echo,
pause
exit /b
:: put the :timediff function here
Output:
2147483647 centiseconds equals to 5965:13:56.47
Using a single function with the possibility of custom unit of measure or formatted.
Each time the function is called without parameters we restarted the initial time.
#ECHO OFF
ECHO.
ECHO DEMO timer function
ECHO --------------------
SET DELAY=4
:: First we call the function without any parameters to set the starting time
CALL:timer
:: We put some code we want to measure
ECHO.
ECHO Making some delay, please wait...
ECHO.
ping -n %DELAY% -w 1 127.0.0.1 >NUL
:: Now we call the function again with the desired parameters
CALL:timer elapsed_time
ECHO by Default : %elapsed_time%
CALL:timer elapsed_time "s"
ECHO in Seconds : %elapsed_time%
CALL:timer elapsed_time "anything"
ECHO Formatted : %elapsed_time% (HH:MM:SS.CS)
ECHO.
PAUSE
:: Elapsed Time Function
:: -----------------------------------------------------------------------
:: The returned value is in centiseconds, unless you enter the parameters
:: to be in another unit of measure or with formatted
::
:: Parameters:
:: <return> the returned value
:: [formatted] s (for seconds), m (for minutes), h (for hours)
:: anything else for formatted output
:: -----------------------------------------------------------------------
:timer <return> [formatted]
SetLocal EnableExtensions EnableDelayedExpansion
SET _t=%time%
SET _t=%_t::0=: %
SET _t=%_t:,0=, %
SET _t=%_t:.0=. %
SET _t=%_t:~0,2% * 360000 + %_t:~3,2% * 6000 + %_t:~6,2% * 100 + %_t:~9,2%
SET /A _t=%_t%
:: If we call the function without parameters is defined initial time
SET _r=%~1
IF NOT DEFINED _r (
EndLocal & SET TIMER_START_TIME=%_t% & GOTO :EOF
)
SET /A _t=%_t% - %TIMER_START_TIME%
:: In the case of wanting a formatted output
SET _f=%~2
IF DEFINED _f (
IF "%_f%" == "s" (
SET /A "_t=%_t% / 100"
) ELSE (
IF "%_f%" == "m" (
SET /A "_t=%_t% / 6000"
) ELSE (
IF "%_f%" == "h" (
SET /A "_t=%_t% / 360000"
) ELSE (
SET /A "_h=%_t% / 360000"
SET /A "_m=(%_t% - !_h! * 360000) / 6000"
SET /A "_s=(%_t% - !_h! * 360000 - !_m! * 6000) / 100"
SET /A "_cs=(%_t% - !_h! * 360000 - !_m! * 6000 - !_s! * 100)"
IF !_h! LSS 10 SET "_h=0!_h!"
IF !_m! LSS 10 SET "_m=0!_m!"
IF !_s! LSS 10 SET "_s=0!_s!"
IF !_cs! LSS 10 SET "_cs=0!_cs!"
SET "_t=!_h!:!_m!:!_s!.!_cs!"
SET "_t=!_t:00:=!"
)
)
)
)
EndLocal & SET %~1=%_t%
goto :EOF
A test with a delay of 94 sec
DEMO timer function
--------------------
Making some delay, please wait...
by Default : 9404
in Seconds : 94
Formatted : 01:34.05 (HH:MM:SS.CS)
Presione una tecla para continuar . . .
CMD doesn't have time arithmetic. The following code, however gives a workaround:
set vid_time=11:07:48
set srt_time=11:16:58
REM Get time difference
set length=%vid_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t1=!h!+!m!+!s!
set length=%srt_time%
for /f "tokens=1-3 delims=:" %i in ("%length%") do (
set /a h=%i*3600
set /a m=%j*60
set /a s=%k
)
set /a t2=!h!+!m!+!s!
cls
set /a diff=!t2!-!t1!
Above code gives difference in seconds. To display in hh:mm:ss format, code below:
set ss=!diff!
set /a hh=!ss!/3600 >nul
set /a mm="(!ss!-3600*!hh!)/60" >nul
set /a ss="(!ss!-3600*!hh!)-!mm!*60" >nul
set "hh=0!hh!" & set "mm=0!mm!" & set "ss=0!ss!"
echo|set /p=!hh:~-2!:!mm:~-2!:!ss:~-2!
set START=23:05:15
set END=07:02:05
set options="tokens=1-4 delims=:."
for /f %options% %%a in ("%start%") do set start_h=%%a&set /a start_m=100%%b %% 100&set /a start_s=100%%c %% 100&set /a start_ms=100%%d %% 100
for /f %options% %%a in ("%end%") do set end_h=%%a&set /a end_m=100%%b %% 100&set /a end_s=100%%c %% 100&set /a end_ms=100%%d %% 100
set /a hours=%end_h%-%start_h%
set /a mins=%end_m%-%start_m%
set /a secs=%end_s%-%start_s%
set /a ms=%end_ms%-%start_ms%
if 1%ms% lss 100 set ms=0%ms%
if %ms% lss 0 set /a secs = %secs% - 1 & set /a ms = 100%ms%
if %secs% lss 0 set /a mins = %mins% - 1 & set /a secs = 60%secs%
if %mins% lss 0 set /a hours = %hours% - 1 & set /a mins = 60%mins%
if %hours% lss 0 set /a hours = 24%hours%
set hours=0%hours%
set hours=%hours:~-2%
set mins=0%mins%
set mins=%mins:~-2%
set secs=0%secs%
set secs=%secs:~-2%
set /a totalsecs = %hours%*3600 + %mins%*60 + %secs%
echo Command took %hours%:%mins%:%secs%.%ms% (%totalsecs%.%ms%s total)
echo %date% %start% - %end% ( %hours%:%mins%:%secs% )
pause

Resources