如何使用 date 命令将“第 40 周星期一”之类的内容转换为 ISO 日期?
我正在玩这样的东西:
date --date='monday week 40' +'%Y-%m-%d'
我要搜索的日期是 2011-10-03。
但我的问题是这个日期字符串无效,所以我需要另一种方法来解决这个问题。
/谢谢
答案1
另一种方法:
date --date "+$((40-$(date +%V)))weeks last monday" +"%F"
- 40 是您搜索的周
- date +%V 返回当前周 (35)
- 40-35 = 5,这是要添加的周数
- 从那里开始,寻找最后一个星期一
答案2
真的很难看,而且可能只适用于 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"
答案3
好的,这是我的尝试。它从其他答案中窃取想法,并试图使逻辑更容易理解。这是基于 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" )
}