2013-03-25 191 views
7

我有巨大的日志文件中提取一周号码列表,它们使用的语法提取:UNIX日期:如何将星期数转换为日期范围(星期一至星期日)?

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

我想创建一个简单的bash功能,可以将这些周数转换为日期范围。我想功能应该接受2个参数:$数量和$一年,例如:

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

回答

9

随着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" 
$ 
+0

完美!非常感谢你。 – hellish 2013-03-25 03:22:01

0

如果有人需要它:我发现了一个更短的方式(不知道是否容易) :

function weekof() { 
     local year=$2 
     local week=`echo $1 | sed 's/^0*//'` # Fixes random bug 
     local dateFormat="+%a %b %d %Y" 
     # Offset is the day of week, so we can calculate back to monday 
     local offset="`date -d "$year/01/01 +$((week - 1)) week" "+%u"`" 
     echo -n "`date -d "$year/01/01 +$((week - 1)) week +$((1 - $offset)) day" "$dateFormat"`" # Monday 
     echo -n " - " 
     echo "`date -d "$year/01/01 +$((week - 1)) week +$((7 - $offset)) day" "$dateFormat"`" # Sunday } 

我把今年的第一天和n周前往正确的一周的某个地方。 然后,我带着我的工作日回到/前进,以达到星期一和星期日。

+0

您的'2012年12月份产出'周一2012年3月12日 - 2012年3月18日。它应该是“2012年3月19日星期一 - 2012年3月25日星期日”。 – pynexj 2016-01-22 16:23:56

1

如果一个星期的开始是星期天,您可以使用此版本weekof的:

function weekof() 
{ 
    local week=$1 year=$2 
    local week_num_of_Jan_1 week_day_of_Jan_1 
    local first_Sun 
    local date_fmt="+%Y-%m-%d" 
    local sun sat 

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

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

    sun=$(date -d "$first_Sun +$((week - 1)) week" "$date_fmt") 
    sat=$(date -d "$first_Sun +$((week - 1)) week + 6 day" "$date_fmt") 
    echo "$sun $sat" 
} 
1

星期一是一周的第一天,ISO week numbers

function week2date() { 
    local year=$1 
    local week=$2 
    local dayofweek=$3 
    date -d "$year-01-01 +$(($week * 7 + 1 - $(date -d "$year-01-04" +%w) - 3)) days -2 days + $dayofweek days" +"%Y-%m-%d" 
} 

week2date 2017 35 1 
week2date 2017 35 7 

输出:

2017-08-28 
2017-09-03 
+0

这已经在4年前回答了。你的答案带来了什么增值? – 2017-09-01 14:30:50

+0

1.明确指定ISO周数 2.它使用维基百科中描述的算法 3.它更短 – 2017-09-04 06:40:00

+0

好吧,够公平! – 2017-09-04 07:07:31

相关问题