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

后端 未结 17 1852
臣服心动
臣服心动 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:08

    DST aware solution:

    Manipulating the Timezone is possible for changing the clock some hours. Due to the daylight saving time, 24 hours ago can be today or the day before yesterday.

    You are sure that yesterday is 20 or 30 hours ago. Which one? Well, the most recent one that is not today.

    echo -e "$(TZ=GMT+30 date +%Y-%m-%d)\n$(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
    

    The -e parameter used in the echo command is needed with bash, but will not work with ksh. In ksh you can use the same command without the -e flag.

    When your script will be used in different environments, you can start the script with #!/bin/ksh or #!/bin/bash. You could also replace the \n by a newline:

    echo "$(TZ=GMT+30 date +%Y-%m-%d)
    $(TZ=GMT+20 date +%Y-%m-%d)" | grep -v $(date +%Y-%m-%d) | tail -1
    
    0 讨论(0)
  • 2020-11-30 18:08
    date +%Y:%m:%d|awk -vFS=":" -vOFS=":" '{$3=$3-1;print}'
    2009:11:9
    
    0 讨论(0)
  • 2020-11-30 18:10

    If you have BSD (OSX) date you can do it like this:

    date -j -v-1d
    Wed Dec 14 15:34:14 CET 2011
    

    Or if you want to do date calculations on an arbitrary date:

    date -j -v-1d -f "%Y-%m-%d" "2011-09-01" "+%Y-%m-%d"
    2011-08-31
    
    0 讨论(0)
  • 2020-11-30 18:13

    Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.

    I find out I can get the previous date with little trick on timezone.

    DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
    echo $DATE
    
    0 讨论(0)
  • 2020-11-30 18:16

    MAC OSX

    For yesterday's date:

    date -v-1d +%F
    

    where 1d defines current day minus 1 day. Similarly,

    date -v-1w +%F - for previous week date

    date -v-1m +%F - for previous month date

    IF YOU HAVE GNU DATE,

    date --date="1 day ago"
    

    More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html

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

    Use Perl instead perhaps?

    perl -e 'print scalar localtime( time - 86400 ) . "\n";'
    

    Or, use nawk and (ab)use /usr/bin/adb:

    nawk 'BEGIN{printf "0t%d=Y\n", srand()-86400}' | adb
    

    Came across this too ... insane!

    /usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",$2);printf "0t%d=Y\n", $2-86400}' | adb
    
    0 讨论(0)
提交回复
热议问题