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?
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.
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.
let DIFF=(`date +%s -d 20120203`-`date +%s -d 20120115`)/86400 echo $DIFF
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)
date $2 -d @0$diff #Pad diff with leading zero
Where $2
again is a date format see for example here
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With