且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

UNIX日期:如何将星期数(日期+%W)转换为日期范围(星期一至星期日)?

更新时间:2023-01-28 15:55:07

使用GNU date:

$ cat weekof.sh
function weekof()
{
    local week=$1 year=$2
    local week_num_of_Jan_1 week_day_of_Jan_1
    local first_Mon
    local date_fmt="+%a %b %d %Y"
    local mon sun

    week_num_of_Jan_1=$(date -d $year-01-01 +%W)
    week_day_of_Jan_1=$(date -d $year-01-01 +%u)

    if ((week_num_of_Jan_1)); then
        first_Mon=$year-01-01
    else
        first_Mon=$year-01-$((01 + (7 - week_day_of_Jan_1 + 1) ))
    fi

    mon=$(date -d "$first_Mon +$((week - 1)) week" "$date_fmt")
    sun=$(date -d "$first_Mon +$((week - 1)) week + 6 day" "$date_fmt")
    echo "\"$mon\" - \"$sun\""
}

weekof $1 $2
$ bash weekof.sh 12 2012
"Mon Mar 19 2012" - "Sun Mar 25 2012"
$ bash weekof.sh 1 2018
"Mon Jan 01 2018" - "Sun Jan 07 2018"
$


注意:

正如OP所述,周号date +%W获取.根据GNU日期的手册:


NOTE:

As the OP mentions, the week number is got by date +%W. According to GNU date's manual:

%W:一年中的第几周,星期一为一周的第一天(00..53)

%W: week number of year, with Monday as first day of week (00..53)

所以:

  1. 每个星期从星期一开始.
  2. 如果1月1日是星期一,那么第一周将是第一周.
  3. 如果1月1日不是星期一,那么前几天将是第0周,而第1周将从第一个星期一开始.
  1. Each week would start from Mon.
  2. If Jan 1 is Mon, then the first week will be week #1.
  3. If Jan 1 is not Mon, then the first few days will be week #0 and the week #1 starts from the first Mon.