0

I was hoping to get some help with finding the difference in days between two dates.

Date 1: Sysdate

Date2: Mar 20 2022 (future)

What I was trying to do is convert it to EPOCH time, subtract and then divide by 86400 to get the number of days between the two dates. However, I've having issues with the systax. Here's what I've tried:

days_remaining=('date "+%s" -d "Mar 20 2022"'-'date "+%s" -d "$(date '+%b %d %Y')"')/86400 

But the above isn't working. Any assistance would be appreciated.

mouviciel
  • 66,855
  • 13
  • 106
  • 140
Shak
  • 103
  • 8
  • Does this answer your question? [How to find the difference in days between two dates?](https://stackoverflow.com/questions/4946785/how-to-find-the-difference-in-days-between-two-dates) – Siddharth Dushantha Jul 02 '21 at 06:43

2 Answers2

2

To do calculations in bash you need an arithmetic context (( )). Also, to execute your date commands you have to put them inside $() instead of string quotes ''.

By the way: The last date command in date "+%s" -d "$(date '+%b %d %Y') isn't necessary. date -d 0:00 +%s will print the same unix time.

(( days_remaining = ($(date -d "Mar 20 2022" +%s) - $(date -d 0:00 +%s)) / 86400 )) 
Socowi
  • 25,550
  • 3
  • 32
  • 54
  • We have to add 1 to the result, since `Mar 20 2022` will have 0:00 p.m. as time set when the current date will have the current time as time set. When the division by 86400 will occur, the difference will be truncated by one day. You can check this by trying to compute the remaining days until tomorrow instead of until `Mar 20 2022`. The result should be `1` but the formula above gives `0`. – Pierre François Jul 02 '21 at 08:02
  • 1
    @PierreFrançois Thank you. Very good observation. Always adding 1d would give a wrong result in the rare case where the current time is exactly midnight (`00:00`). Therefore I rounded up to whole days by adding 24h-1s. – Socowi Jul 02 '21 at 15:04
  • 1
    On the other hand, using `date -d 0:00` to get the unix time of today's start of the day may be easier. I changed the answer again. – Socowi Jul 02 '21 at 15:12
0

you can use this

days_remaining=$(($(($(date "+%s" -d "Mar 20 2022") - $(date "+%s" -d "$(date '+%b %d %Y')"))) /  86400))
thatguy
  • 233
  • 3
  • 12