Date

日期:以年和周數開頭,如何獲得星期一的日期

  • February 15, 2022

如何獲取特定周星期一的 ISO 日期?例如,2021 年第 32 週的星期一?

我知道如果我跑步,date -dmonday +%Y%m%d我會得到本週的星期一日期。如何將2021and32作為變數傳遞,並獲取該周星期一的日期?

這似乎工作正常。

#! /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

date.sh上面的腳本在哪裡。

維基百科有一篇關於 ISO 週日期 的文章 “第一周”被定義為第一個星期四。文章指出,這相當於 1 月 4 日總是在第 1 週。GNU date 允許您給出日期,這樣您就可以date -d "Jan 4 2021 +3 weeks"第 4 週獲得日期,通常不是星期一。

使用日期我們可以找到一周中的哪一天,並使用它來調整要請求的日期。

#!/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)"

因此,對於 2021 年,這顯示第 1 週的星期一是 2021-01-04,而對於 2020 年,它是 2019-12-30(即上一年年底)

引用自:https://unix.stackexchange.com/questions/688955