在 Bash 中获取日期(当前时间前一天)
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/1706882/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get the date (a day before current time) in Bash
提问by conandor
How can I print the date which is a day before current time in Bash?
如何在 Bash 中打印当前时间前一天的日期?
采纳答案by conandor
Sorry not mentioning I on Solaris system. As such, the -date switch is not available on Solaris bash.
抱歉没有在 Solaris 系统上提及 I。因此,-date 开关在 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
回答by ghostdog74
if you have GNU date and i understood you correctly
如果您有 GNU 日期并且我正确理解您
$ date +%Y:%m:%d -d "yesterday"
2009:11:09
or
或者
$ date +%Y:%m:%d -d "1 day ago"
2009:11:09
回答by Jacob Persson
If you have BSD (OSX) date
you can do it like this:
如果你有 BSD (OSX),date
你可以这样做:
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
回答by silent
date --date='-1 day'
回答by Maverick
MAC OSX
MAC OSX
For yesterday's date:
对于昨天的日期:
date -v-1d +%F
where 1ddefines current day minus 1 day. Similarly,
其中1d定义当前日期减去 1 天。相似地,
date -v-1w +%F- for previous week date
date -v-1w +%F- 上周日期
date -v-1m +%F- for previous month date
date -v-1m +%F- 上个月的日期
IF YOU HAVE GNU DATE,
如果您有 GNU 日期,
date --date="1 day ago"
More info: https://www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html
更多信息:https: //www.cyberciti.biz/tips/linux-unix-get-yesterdays-tomorrows-date.html
回答by alpana
Well this is a late answer,but this seems to work!!
嗯,这是一个迟到的答案,但这似乎有效!!
YESTERDAY=`TZ=GMT+24 date +%d-%m-%Y`;
echo $YESTERDAY;
回答by Peter Lindqvist
回答by martin clayton
Use Perl instead perhaps?
也许改用 Perl?
perl -e 'print scalar localtime( time - 86400 ) . "\n";'
Or, use nawk and (ab)use /usr/bin/adb:
或者,使用 nawk 和(ab)使用 /usr/bin/adb:
nawk 'BEGIN{printf "0t%d=Y\n", srand()-86400}' | adb
Came across thistoo ... insane!
也遇到了这个……疯了!
/usr/bin/truss /usr/bin/date 2>&1 | nawk -F= '/^time\(\)/ {gsub(/ /,"",);printf "0t%d=Y\n", -86400}' | adb
回答by DigitalRoss
date --date='-1 day'
date --date='-1 day'
回答by medoix
#!/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