开发者

Date calculation using GNU date

开发者 https://www.devze.com 2023-02-25 14:10 出处:网络
Using the GNU date command line utility, I know: how to substract 3 days from any given date: date -d \"20110405 -3 days\" \"+%Y%m%d\"

Using the GNU date command line utility, I know:

  • how to substract 3 days from any given date:

    date -d "20110405 -3 days" "+%Y%m%d"

    20110402

  • how to get the last Friday from today:

    date -d "last friday" "+%Y%m%d"

    20110408

But I don't kno开发者_如何学Cw how to get the last Friday from any given date:

date -d "20110405 last friday" "+%Y%m%d"

Simply returns the given date:

20110405

Any ideas on how to do this? If a one-liner is not possible a few lines of script would also be helpful.


Ugly, but one line:

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.

I don't like that it repeats the date string, but hopefully it goes some way to helping.


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)

# 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"
0

精彩评论

暂无评论...
验证码 换一张
取 消