UNIX日期:如何将星期数(日期+%W)转换为日期范围(星期一至星期日)? [英] UNIX date: How to convert week number (date +%W) to a date range (Mon-Sun)?
本文介绍了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)转换为日期范围(星期一至星期日)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文