微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

bash – UNIX日期:如何将周数转换为日期范围(Mon-Sun)?

我有从大日志文件提取的周数列表,它们是使用语法提取的:
$date --date="Wed Mar 20 10:19:56 2012" +%W;
12

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

$week() { ......... }
$number=12; year=2012
$week $number $year
"Mon Mar 19 2012" - "Sun Mar 25 2012"
使用GNU日期:
$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"
$

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐