I realize there are tons of questions and answers involving date calculation, but I haven't found a solution to the issue on OS X/macOS. I would like to calculate the time difference between two dates and times, but I must have the syntax incorrect.
now=$(date +"%b %d %Y %H:%M:%S")
end=$(date +"Dec 25 2017 08:00:00")
dif=$(date -j -f "%b %d %Y %H:%M:%S" "$end" - "$now")
echo $dif
# Mon Dec 25 08:00:00 MST 2017
It returns only the $end value, so I'm not sure how to actually calculate the difference in time.
But as you mentioned actual sleep value and print output are different. For example if I run ` a=$(date +%s%N) sleep 1.235 b=$(date +%s%N) diff=$((b-a)) printf "%d. %d seconds passed\n" "${diff:0: -9}" "${diff: -9:3}" ` It says 1.241 seconds passed .
The ideal way is convert the current time into EPOCH and also the date you need also in EPOCH and get the diff (This works on bash on macOS Sierra)
dudeOnMac:~ $ date +%s
1512757414
dudeOnMac:~ $ date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s
1514169000
So now storing in the variables as you wanted
end=$(date -j -f "%b %d %Y %H:%M:%S" "Dec 25 2017 08:00:00" +%s)
now=$(date +%s)
printf '%d seconds left till target date\n' "$(( (end-now) ))"
printf '%d days left till target date\n' "$(( (end-now)/86400 ))"
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