Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the difference between two dates under bash [duplicate]

Tags:

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?

like image 237
owagh Avatar asked Jan 25 '12 19:01

owagh


People also ask

How do you subtract dates in bash?

Set it to the number of days that you want to subtract. Very slight improvement to the command - date --date="${dataset_date} -${date_diff} day" +%Y-%m-%d.

How do you subtract dates in unix?

The easiest way is to convert the date to a unix time_t value (i.e. seconds since the beginning of the epoch, or '1-1-1970 00:00:00'), and then substract 30 days * 86400 seconds per day from that number. e.g. the following example uses set -x so that you can see the value of the D variable as it changes.


2 Answers

let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400 echo $DIFF 
like image 59
Eugen Rieck Avatar answered Sep 22 '22 13:09

Eugen Rieck


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

like image 23
Cadoiz Avatar answered Sep 25 '22 13:09

Cadoiz