Answers:
真的很丑,可能只适用于GNU date
:
date -d "$( date -d "$( date +'%Y-01-01' ) +40 weeks") -$( date -d "$( date +'%Y-01-01' ) +40 weeks" +'%w' ) days+1 day" +'%Y-%m-%d'
仅针对10月3日的示例进行了测试,在某些其他情况下可能会失败。
更新:如果您有非英语语言环境,则需要指定内部日期的输出才能开始工作。(%F只是YYYY-MM-DD)。
date -d "$(date -d "$(date +'%Y-01-01') +40 weeks" +"%F") -$(date -d "$(date +'%Y-01-01') +40 weeks" +%w) days +1 day" +"%F"
替代方法:
date --date "+$((40-$(date +%V)))weeks last monday" +"%F"
date +%V
return 41
),则--date
参数值将是+-1weeks last monday
,实际上是两周前,而不是7天前。
date -d 'last monday'
。它将在昨天返回。如果您昨天运行它,您认为它会怎么说?
好,这是我的尝试。它从其他答案中窃取了想法,并试图使逻辑更易于遵循。这是基于ISO 8601系统的,因此,如果您居住在美国或加拿大等国家,那将是不正确的,但应该可以轻松地针对这些国家进行调整。
# sets $week_start to a representation of Monday of the given week
# number formatted via the given format, and similarly sets
# $week_end to Friday of the same week.
get_week_range () {
week_num="$1" date_format="$2"
# Most of the world adhere to ISO 8601 which states that weeks begin on Monday
# and Jan 4th is always in week #1:
#
# http://en.wikipedia.org/wiki/ISO_week_date
#
# For other week numbering systems (e.g. USA, Canada), see:
#
# http://en.wikipedia.org/wiki/Seven-day_week#Week_numbering
day_in_week_1=$( date +'%Y-01-04' )
day_num_in_week_1=$( date -d $day_in_week_1 +%u ) # 1 is Monday
days_from_week_1_start=$(( $day_num_in_week_1 - 1 ))
# This is a Monday:
start_of_week_1=$( date -d "$day_in_week_1 - $days_from_week_1_start days" +%F )
week_delta="$(( $week_num - 1 ))"
# Monday:
week_start=$( date -d "$start_of_week_1 + $week_delta weeks" +"$date_format" )
# Friday:
week_end=$( date -d "$start_of_week_1 + $week_delta weeks + 4 days" +"$date_format" )
}
%V
使用的格式顺序报告了ISO周编号。