I need to somehow use the date command in bash or another utility to print out the date and time, 5 minutes before and 5 minutes after a given value. For example:
i
If you want to do this for the current time +/-5 minutes and you use Bash 4.2 or newer, you can do it without external tools:
$ printf -v now '%(%s)T'
$ echo "$now"
1516161094
$ f='%a %b %d %R'
$ printf "%($f)T %($f)T %($f)T\n" "$((now-300))" "$now" "$((now+300))"
Tue Jan 16 22:46 Tue Jan 16 22:51 Tue Jan 16 22:56
The %(datefmt)T
formatting string of printf allows to print date-time strings. If the argument is skipped (like here) or is -1
, the current time is used.
%s
formats the time in seconds since the epoch, and -v now
stores the output in now
instead of printing it.
f
is just a convenience variable so I don't have to repeat the formatting string for the output three times.
Since the argument for this usage of printf
has to be in seconds since the epoch, you're stuck with external tools to convert an input string like Thu Dec 19 14:10
into that format and you'd replace
printf -v now '%(%s)T'
with, for example, any of
now=$(date '+%s' -d 'Thu Dec 19 14:10') # GNU date
now=$(date -j -f '%a %b %d %T' 'Thu Dec 19 14:10' '+%s') # macOS date
If you're using bash under linux, you can use the -d
parameter to perform date manipulation on an existing date:
Get the EPOCH time for the date in question:
EPOCH=$(date -d 'Thu Dec 19 14:10' '+%s')
This gives you the time, in seconds, since the EPOCH (typically 01/01/1970)
Now you can use simple math to subtract or add 5 minutes (in seconds) to the EPOCH time
NEW_EPOCH=$(($EPOCH - 300))
obviously, there are 300 seconds in 5 minutes
Now convert this NEW_EPOCH back into a human readable date
NEW_DATE=$(date -d "1970-01-01 ${NEW_EPOCH} sec")
NOTE that this only works on unix systems which support the date -d option (i.e. Linux)
You can achieve this, for the current time, by typing.
$ date --date='5 minutes ago'; date; date --date='5 minutes'
Qui Dez 19 16:09:17 BRST 2013
Qui Dez 19 16:14:17 BRST 2013
Qui Dez 19 16:19:17 BRST 2013
To use a specific date (ex 1978/01/10).
$ date --date='1978-01-10 + 5 minutes'
Ter Jan 10 00:05:00 BRT 1978
With GNU date
, you can do a simple form of date/time arithmetic with the argument to the --date
option:
$ date --date 'now + 5 minutes'
With BSD date
(at least, the version that ships with Mac OS X), the -v
option allows you to do something similar, but only with the current time:
$ date -v +5M
$ date -v -5M
Otherwise, you need to perform the math explicitly after converting the time to a UNIX timestamp (seconds since Jan 1, 1970):
$ date -r $(( $(date +%s) + 300 )) # 5 minutes (300 seconds) from now
$ date -r $(( $(date +%s) - 300 )) # 5 minutes ago