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

后端 未结 4 855
刺人心
刺人心 2021-01-01 16:03

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

4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-01 16:42

    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
    

提交回复
热议问题