subtract 1 hour from date in unix shell script

前端 未结 8 1063
鱼传尺愫
鱼传尺愫 2020-12-16 08:42

I have the following in a shell script. How can I subtract one hour while retaining the formatting?

DATE=`date \"+%m/%d/%Y -%H:%M:%S\"`
相关标签:
8条回答
  • 2020-12-16 09:40

    If you need change timezone before subtraction with new format too:

    $(TZ=US/Eastern date -d '1 hour ago' '+%Y-%m-%d %H:%M')
    
    0 讨论(0)
  • 2020-12-16 09:46
    date -v-60M "+%m/%d/%Y -%H:%M:%S"
    
    DATE=`date -v-60M "+%m/%d/%Y -%H:%M:%S"`
    

    If you have bash version 4.4+ you can use bash's internal date printing and arithmetics:

    printf "current date: %(%m/%d/%Y -%H:%M:%S)T\n"
    printf "date - 60min: %(%m/%d/%Y -%H:%M:%S)T\n" $(( $(printf "%(%s)T") - 60 * 60 ))
    

    The $(printf "%(%s)T") prints the epoch seconds, the $(( epoch - 60*60 )) is bash-aritmetics - subtracting 1hour in seconds. Prints:

    current date: 04/20/2017 -18:14:31
    date - 60min: 04/20/2017 -17:14:31
    
    0 讨论(0)
提交回复
热议问题