How do I get the difference between two dates under bash
Proposing this solution which uses bc
:
current="$(date +%s.%N)" #current date, precise to nanoseconds
old="$(date +%s.%N -d "$(sh some_script_that_gives_a_date.sh)")" #convert output to ns too
diff=$(echo "$current-$old" |bc)
date +%s.%N -d $1
takes an arbitrary date and converts it to a given format (as in this case +%s.%N
, a float
of seconds). Be aware that
-d is not a part of POSIX date. [But] as long as [you're] not working on distributions like Solaris ([OP] has tagged it linux and not unix) [you] should be good. :)
(comment by jaypal singh on this answer)
To convert it back to human-readable, you can use:
date $2 -d @0$diff #Pad diff with leading zero
Where $2
again is a date format see for example here
let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400
echo $DIFF