Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to generate consecutive week range dates for n past weeks

Tags:

date

bash

awk

I would like to generate a list of n week range dates going backward from the current week, like so

2014-03-22 2014-03-28
2014-03-15 2014-03-21
2014-03-08 2014-03-14
etc.

where the first date in each row is the beginning of the weekly period, which starts Saturday and ends Friday.

My preference would be to do this in a shell script, using awk or other Unix tools. The field delimiter doesn't matter, but the records should be one per line.

like image 416
dan Avatar asked Dec 09 '25 09:12

dan


2 Answers

n=5    
for i in $(seq 0 $((n-1))); do
    echo "$(date -d "last saturday -$i weeks" +"%Y-%m-%d") $(date -d "friday -$i weeks" +"%Y-%m-%d")"; 
done

Output:

2014-03-22 2014-03-28
2014-03-15 2014-03-21
2014-03-08 2014-03-14
2014-03-01 2014-03-07
2014-02-22 2014-02-28
like image 114
Josh Jolly Avatar answered Dec 12 '25 07:12

Josh Jolly


If GNU date is a problem, how about Perl? This should use only standard modules, for a recent-ish version of Perl

use v5.10;
use Time::Piece;
use Time::Seconds;

$, = " ";

# get the previous saturday, unless today is saturday
my $day = localtime;
$day -= $day->wday * ONE_DAY unless $day->wday == 6;

while (1) {
    say $day->strftime("%F"), ($day + 6*ONE_DAY)->strftime("%F"); 
    $day -= 7 * ONE_DAY;
}
like image 33
glenn jackman Avatar answered Dec 12 '25 05:12

glenn jackman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!