How to calculate time difference

Hi Gurus,

I need to calculate time between two column. I don't know how to deal with these records which passed mid-night. for example: 2nd and 4th records it started at Jun 21st, end at Jun 22nd.

Thanks in advance for any advice you can provide me

06/21/2020 21:42:24  06/21/2020 21:45:24  --- 3 minutes    
06/21/2020 22:42:25  06/22/2020 01:28:41  --- 2 hrs 46 minutes
06/21/2020 21:42:25  06/21/2020 22:42:32  --- 1 hr  
06/21/2020 23:42:25  06/22/2020 02:42:29  --- 3 hrs

What is difficult?
you subtract the first from 24 Hours, the result is added to second e.g. 2nd record:

24:00:00 - 22:42:25 = 01:17:35 
01:17:35 + 01:28:41= 02:46...

You need to extract each date, convert then in "seconds since 01/01/1970" and make substraction between the two amount of seconds.
Use something like this :

d1 = $(date -d "06/21/2020 21:42:24" +%s)
d2 = $(date -d "06/21/2020 21:45:24" +%s)
date -d@$(($d2 - $d1)) -u +"%H hours %M minutes %S seconds"
1 Like

Hello @green_k, on forums we do encourage users to do add their efforts which they have put in order to solve their own problem, so kindly do add the same in your question and let us know then.

Thanks,
R. Singh

1 Like

thanks for your quick reply.

I run command

date -d "06/21/2020 21:42:24" +%s and got below error:
date: illegal option -- d
usage:  date [-u] mmddHHMM[[cc]yy][.SS]
        date [-u] [+format]
        date -a [-]sss[.fff]

my os is SunOS 5.10 Generic_150400-64 sun4v sparc sun4v

The suggestion you were given is GNU-specific and you have Solaris.
Try the following OF-agnostic and compare:

d1=$(echo '06/21/2020 21:42:24' | awk -F'[/ :]' '{printf "%d\n", $1*2629743 + $2*86400 + ($3-1970)*31556926 +$4*3600 +$5*60+$6}')

Same for d2.
Furthermore, I believe the last date -d@$((.... is also GNU-specific. You'll have to implement it yourself.

This topic was automatically closed 60 days after the last reply. New replies are no longer allowed.