Get the date (a day before current time) in Bash

后端 未结 17 1839
臣服心动
臣服心动 2020-11-30 17:54

How can I print the date which is a day before current time in Bash?

相关标签:
17条回答
  • 2020-11-30 18:04

    Try the below code , which takes care of the DST part as well.

    if [ $(date +%w) -eq $(date -u +%w) ]; then
      tz=$(( 10#$gmthour - 10#$localhour ))
    else
      tz=$(( 24 - 10#$gmthour + 10#$localhour ))
    fi
    echo $tz
    myTime=`TZ=GMT+$tz date +'%Y%m%d'`
    

    Courtsey Ansgar Wiechers

    0 讨论(0)
  • 2020-11-30 18:05

    if you have GNU date and i understood you correctly

    $ date +%Y:%m:%d -d "yesterday"
    2009:11:09
    

    or

    $ date +%Y:%m:%d -d "1 day ago"
    2009:11:09
    
    0 讨论(0)
  • 2020-11-30 18:05
    date -d "yesterday" '+%Y-%m-%d'
    

    or

    date=$(date -d "yesterday" '+%Y-%m-%d')
    echo $date
    
    0 讨论(0)
  • 2020-11-30 18:06
    date --date='-1 day'
    
    0 讨论(0)
  • 2020-11-30 18:07

    Advanced Bash-scripting Guide

    date +%Y:%m:%d -d "yesterday"
    

    For details about the date format see the man page for date

    date --date='-1 day'
    
    0 讨论(0)
  • 2020-11-30 18:08

    You could do a simple calculation, pimped with an regex, if the chosen date format is 'YYYYMM':

    echo $(($(date +"%Y%m") - 1)) | sed -e 's/99$/12/'
    

    In January of 2020 it will return 201912 ;-) But, it's only a workaround, when date does not have calculation options and other dateinterpreter options (e.g. using perl) not available ;-)

    0 讨论(0)
提交回复
热议问题