如何在Bash中打印当前时间前一天的日期?


当前回答

#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day

其他回答

#!/bin/bash
OFFSET=1;
eval `date "+day=%d; month=%m; year=%Y"`
# Subtract offset from day, if it goes below one use 'cal'
# to determine the number of days in the previous month.
day=`expr $day - $OFFSET`
if [ $day -le 0 ] ;then
month=`expr $month - 1`
if [ $month -eq 0 ] ;then
year=`expr $year - 1`
month=12
fi
set `cal $month $year`
xday=${$#}
day=`expr $xday + $day`
fi
echo $year-$month-$day

对不起,在Solaris系统上没有提到我。 因此,-date开关在Solaris bash上不可用。

我发现我可以得到之前的日期与小技巧的时区。

DATE=`TZ=MYT+16 date +%Y-%m-%d_%r`
echo $DATE

如果你有GNU日期,我理解正确

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

or

$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
yesterday=`date -d "-1 day" %F`

将昨天的日期(YYYY-MM-DD格式)放入变量$yesterday。

date --date='-1 day'