#! /bin/bash
year=$1
week=$2
read s w d < <(date -d $year-01-01T13:00 '+%s %V %u')
(( s += ((week - w) * 7 - d + 1) * 24 * 60 * 60 ))
date -d @$s '+%V:%w %Y-%m-%d %a'
经测试
for y in {1970..2022} ; do
maxw=$(date +%V -d $y-12-31)
if (( max == 1 )) ; then # The last day of the year belongs to week #1.
max=52
fi
for ((w=1; w<=maxw; ++w)) ; do
date.sh $y $w | tail -n1 | grep -q "0\?$w:1 " || echo $y $w
done
done
#!/bin/bash
# pass in $1 as the week number and $2 as the year
# Make sure we are no going to be bothered by daylight saving time
# Use explicit time idea from https://unix.stackexchange.com/a/688968/194382
export TZ=UTC
# Jan 4th is always in week 1. ask for the day of the week that is
# $1-1 weeks ahead. %u gives 1 for Monday, 2 for tuesday, ...
weekday=$(date -d"13:00 Jan 4 $2 +$(($1 -1)) weeks" "+%u")
# So now just go back 0 days for a monday, 1 day for tuesday ...
# Could use Jan 5 and go back 1 day for monday instead.
date -d"13:00 Jan 4 $2 +$(($1 -1)) weeks -$((weekday -1)) days" "+%a %F (%G %V)"
这似乎工作正常。
经测试
date.sh
上面的脚本在哪里。维基百科有一篇关于 ISO 周日期 的文章 “第一周”被定义为第一个星期四。文章指出,这相当于 1 月 4 日总是在第 1 周。GNU date 允许您给出日期,这样您就可以在
date -d "Jan 4 2021 +3 weeks"
第 4 周获得日期,通常不是星期一。使用日期我们可以找到一周中的哪一天,并使用它来调整要请求的日期。
因此,对于 2021 年,这显示第 1 周的星期一是 2021-01-04,而对于 2020 年,它是 2019-12-30(即上一年年底)
这至少从 2000 年到 2025 年有效:
LC_ALL=C
前缀消除了影响locale
。