Wednesday, February 27, 2008

Time between two dates - using BASH


This was posted in http://www.unix.com/shell-programming-scripting/

---------------------------------------------------------
Hi,


Please help me out in creating a script which will subtract Tue, Feb 26, 2008 01:38:25 AM from Mon, Feb 25, 2008 09:30:03 PM and will give me out put in the format hh:mm:ss.

I tried datecalc.It doesnt work for this format.
----------------------------------------------

And here is my solution: The idea is to convert both the times to epoch and get the diff in seconds and then convert the seconds to hh:mm:ss format using awk.


$ cat datediff.sh
#!/bin/sh

D1=`date +%s -d "Feb 26, 2008 01:38:25 AM"`
D2=`date +%s -d "Feb 25, 2008 09:30:03 PM"`
((diff_sec=D1-D2))
echo - | awk '{printf "%d:%d:%d","'"$diff_sec"'"/(60*60),"'"$diff_sec"'"%(60*60)/60,"'"$diff_sec"'"%60}'

$ sh datediff.sh
4:8:22

5 comments:

mahesh said...

Great man ...!!
Thank you.

sujith said...

Thanks ... excellent one.
Can you please explain the script too..

Jadu Saikia said...

@Sujith,

This will be more easy to understand:

#!/bin/sh

D1=$(date +%s -d "Feb 26, 2008 01:38:25 AM")
D2=$(date +%s -d "Feb 25, 2008 09:30:03 PM")

((diff_sec=D1-D2))

echo $diff_sec | awk '{printf "%d:%d:%d\n",$1/(60*60),$1%(60*60)/60,$1%60}'


So,
A.
In the first two lines I am converting human date to unix epoch using date command +%s option.

e.g.
$ date +%s -d "Feb 26, 2008 01:38:25 AM"

Output:
1203970105

B.
((diff_sec=D1-D2))
is D1-D2 arithmetic operation.

C.
Now I am converting diff_sec to h:m:s format using awk printf.

Hope this helps.

sujith said...

Yes , thank you.
that helped a lot.

Regards,

Harry said...

I have time with milliseconds also... ((05:12:31,646 to 05:12:31,744)).. so please can you tell for this also ..thaanx in advance.

© Jadu Saikia www.UNIXCL.com