如何获得bash日期脚本以返回相对于当前时间的星期几?

如何获得bash日期脚本以返回相对于当前时间的星期几?

问题描述:

使用bash日期,我可以得到相对于当前时间的星期几。

Using bash date, I can get it to return a day of the week relative to the current time.

date --d='last Sunday' #Returns date of the Sunday before today

我也可以得到它返回一天相对于其他日期

I can also get it to return a day relative to some other date

date --d='02/1/2012 -2 days' #Returns date two days before Feb. 1, 2012

但是如何让它返回一周中的日子相对于一些非当前时间?我想做的是:

but how can I get it to return the day of the week relative to some non-current time? What I want to do is:

date --d='Sunday before 02/1/2012' #Doesn't work! I want Sunday before Feb. 1

如果可能,我甚至希望能够链接字符串可以从新日期引用相对日期:

If possible, I would even like to be able to chain strings so that I can reference relative days from the new date:

# Should return 2 days before the Sunday before Feb. 1, 2012
date --d='Sunday before 02/1/2012 - 2 days'

虽然这个链接不是那么重要。 bash date有什么方法可以根据一周的相对日期返回一天吗?

Though this chaining is not as important. Is there some way for bash date to return a day based on the relative day of the week?

你可以使用一点日数算术:

You can use a little day number arithmetic:

base="02/1/2012"
feb1_dayofweek=$( date -d $base +%w )
target_dayofweek=0   # sunday
date -d "$base - $(( (7 + feb1_dayofweek - target_dayofweek) % 7 )) days"

结果:

Sun Jan 29 00:00:00 EST 2012