Bash script/command to print out date 5 min before/after

Viewed 44050

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:

input:

Thu Dec 19 14:10

output:

Thu Dec 19 14:05 Thu Dec 19 14:10 Thu Dec 19 14:15

I see that the date command can be used to do this on the current date/time, can it be used with a passed value, i.e. not the current date/time?

4 Answers

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
Related