I would like to write a script or function to tell me how many days from now until a given date in the future. What I'm struggling to work out is how to process the given date and compare it with the current date… I'm imagining something like
read -p "enter the date in the format YYYY-MM-DD "
And then I'm assuming I have a string that's meaningless to the shell and I have to do some evaluations like…?? (This is just an example; I guess bc
would be needed)
i=$(($(date +%Y)-${REPLY%%-*}))
j=$(($(date +%m)-${REPLY:5:2}))
k=$(($(date +%d)-${REPLY##*-}))
And then I don't know what to do with those numbers…??
if $i > 1 then assign l=$((i*365)) and else what?? # what about leap years?
Using $j somehow assign m # confused before I've started
Using $k somehow assign n # just as bad
echo $((l+m+n))
I'm surely making it too hard for myself; probably there's a text processing tool that understands dates and can compare them.
How can I do this?
Best Answer
Epoch time
In general, calculations on time are easiest if we first convert time into (Unix) epoch time (seconds from 1-1-1970). In python, we have tools to convert time into epoch time, and back into any date format we prefer.
We can simply set a format, like:
...and define today:
and subsequently write a function to do the job:
Then the output of:
...which is, as mentioned, the number of seconds since 1-1-1970
Calculating the days between two dates
If we do this on both today and our future date, subsequently calculate the difference:
The output will be calculated by date, since we use the format
%Y-%m-%d
. Rounding on seconds would possibly give an incorrect date difference, if we are near 24 hrs for example.Terminal version
...And the Zenity option
And just for fun...
A tiny application. Add it to a shortcut if you use it often.
The script:
orangedays.py
Run it:
To wrap it up
Use for the tiny application script above the following
.desktop
file:orangedays.desktop
in~/.local/share/applications
In the line
set the actual path to the script...