This is a rather old thread, but I discovered something interesting in BusyBox, at least pertaining to adding and subtracting N units of time from a known date. Not so much for going the other way to determine the interval between two known dates though.
I'm stuck on an embedded system with BusyBox and the super handy now - 10 days
notation fails there. In fact, a very limited set of input formats is available for the -d
option.
$ busybox date --help
BusyBox v1.19.0 (2019-07-14 10:52:19 UTC) multi-call binary.
Usage: date [OPTIONS] [+FMT] [TIME]
Display time (using +FMT), or set time
[-s,--set] TIME Set time to TIME
-u,--utc Work in UTC (don't convert to local time)
-R,--rfc-2822 Output RFC-2822 compliant date string
-I[SPEC] Output ISO-8601 compliant date string
SPEC='date' (default) for date only,
'hours', 'minutes', or 'seconds' for date and
time to the indicated precision
-r,--reference FILE Display last modification time of FILE
-d,--date TIME Display TIME, not 'now'
-D FMT Use FMT for -d TIME conversion
Recognized TIME formats:
hh:mm[:ss]
[YYYY.]MM.DD-hh:mm[:ss]
YYYY-MM-DD hh:mm[:ss]
[[[[[YY]YY]MM]DD]hh]mm[.ss]
However, some math can be done on an input date. Given those formats, I found setting the day number of the input date to zero gives you the last day of the previous month:
$ date -d 2020.03.00-12:00
Sat Feb 29 12:00:00 EST 2020
Further, inputting negative numbers keeps subtracting backwards, which I certainly did not expect:
$ date -d 2020.03.-10-12:00
Wed Feb 19 12:00:00 EST 2020
So you can do some quick math on your known date to generate values to feed into the -d
option in the BusyBox date
call:
#!/bin/bash
#Other shells not tested.
start_year=2020
start_month=1
start_day=20
offset_year=-2
offset_month=4
offset_day=5
new_year=$(( $start_year + $offset_year ))
new_month=$(( $start_month + $offset_month ))
new_day=$(( $start_day + $offset_day ))
new_date$( busybox date -d $new_year.$new_month.$new_day-12:00 +%Y-%m-%d )
echo $new_date
Output:
2018-05-25
Can anyone confirm if this also works with GNU, BSD, or MacOS date
? I certainly appreciate that the GNU now - 10 days
is very much better, but I'm interested in making this as portable as possible. I have confirmed that Android is very different (neither approach works there).