How do I get the difference between two dates under bash

47,754

Solution 1

let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400
echo $DIFF

Solution 2

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

Share:
47,754
owagh
Author by

owagh

Updated on August 18, 2022

Comments

  • owagh
    owagh almost 2 years

    Exactly as the question sounds. I want to subtract say 20120115 from 20120203 and get 19 as the answer. What is the best way to implement this in a shell script?