bash 使用 GNU 日期计算日期
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/5655026/
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
Date calculation using GNU date
提问by Ponytech
Using the GNU date command line utility, I know:
使用 GNU date 命令行实用程序,我知道:
how to substract 3 days from any given date:
date -d "20110405 -3 days" "+%Y%m%d"20110402how to get the last Friday from today:
date -d "last friday" "+%Y%m%d"20110408
如何从任何给定日期减去 3 天:
date -d "20110405 -3 days" "+%Y%m%d"20110402如何从今天获得最后一个星期五:
date -d "last friday" "+%Y%m%d"20110408
But I don't know how to get the last Friday from any given date:date -d "20110405 last friday" "+%Y%m%d"
Simply returns the given date:20110405
但我不知道如何从任何给定日期获取最后一个星期五:date -d "20110405 last friday" "+%Y%m%d"
只需返回给定日期:20110405
Any ideas on how to do this? If a one-liner is not possible a few lines of script would also be helpful.
关于如何做到这一点的任何想法?如果单行无法实现,那么几行脚本也会有所帮助。
回答by cmbuckley
Ugly, but one line:
丑陋,但有一行:
date -d "20110405 -2 days -$(date -d '20110405' '+%w') days" "+%Y%m%d"
date -d "20110405 -2 days -$(date -d '20110405' '+%w') days" "+%Y%m%d"
EDIT: See comments.
编辑:见评论。
date -d "20110405 -$(date -d "20110405 +2 days" +%u) days" "+%Y%m%d"
Explanation:
解释:
- %w returns day of the week. Friday = 5 so take off 2 more days to get the right offset.
- Works out as "20110405 -x days", where x is the number of days back to last Friday.
- %w 返回星期几。星期五 = 5 所以再起飞 2 天以获得正确的偏移量。
- 计算为“20110405 -x 天”,其中 x 是回到上周五的天数。
I don't like that it repeats the date string, but hopefully it goes some way to helping.
我不喜欢它重复日期字符串,但希望它在某种程度上有所帮助。
回答by roblogic
Script example (based on the accepted answer)
脚本示例(基于接受的答案)
DT="20170601"
# get the Friday before $DT
# expected value is 20170526
date -d "$DT -`date -d "$DT +2 days" +%u` days" "+%Y%m%d"
Further examples, using undocumented features of GNU date (from unix.com)
更多示例,使用 GNU date 的未记录功能(来自unix.com)
# assign a value to the variable DT for the examples below
DT="2006-10-01 06:55:55"
echo $DT
# add 2 days, one hour and 5 sec to any date
date --date "$DT 2 days 1 hour 5 sec"
# subtract from any date
date --date "$DT 3 days 5 hours 10 sec ago"
date --date "$DT -3 days -5 hours -10 sec"
# or any mix of +/-. What will be the date in 3 months less 5 days?
date --date "now +3 months -5 days"

