Search code examples
bashunixdateshunix-timestamp

UNIX date: How to convert week number (date +%W) to a date range (Mon-Sun)?


I have list of week numbers extracted from huge log file, they were extracted using syntax:

$ date --date="Wed Mar 20 10:19:56 2012" +%W;
12

I want to create a simple bash function which can convert these week numbers to a date range. I suppose function should accept 2 arguments: $number and $year, example:

$ week() { ......... }
$ number=12; year=2012
$ week $number $year
"Mon Mar 19 2012" - "Sun Mar 25 2012"

Solution

  • With 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"
    $
    

    NOTE:

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

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

    So:

    1. Each week starts 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.