Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate Date / Time difference in Bash on macOS

Tags:

date

bash

macos

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.

like image 938
ctfd Avatar asked Dec 08 '17 17:12

ctfd


People also ask

How do you find the time difference in shells?

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 .


1 Answers

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 ))"
like image 186
Inian Avatar answered Oct 20 '22 12:10

Inian