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

编程入门 行业动态 更新时间:2024-10-26 20:29:54
本文介绍了UNIX日期:如何将星期数(日期+%W)转换为日期范围(星期一至星期日)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个从庞大的日志文件中提取的周数列表,它们是使用以下语法提取的:

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

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

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"

推荐答案

使用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月1日是星期一,那么第一周将是第一周.
  • 如果1月1日不是星期一,那么前几天将是第0周,而第1周将从第一个星期一开始.
  • Each week would start from Mon.
  • If Jan 1 is Mon, then the first week will be week #1.
  • If Jan 1 is not Mon, then the first few days will be week #0 and the week #1 starts from the first Mon.
  • 更多推荐

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

    本文发布于:2023-10-28 19:58:06,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1537626.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:日期   星期   转换为   如何将   星期日

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!