Reputation: 348
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.
Upvotes: 10
Views: 6416
Reputation: 85530
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 ))"
Upvotes: 11