javalearner
javalearner

Reputation: 197

Given a month perl should split into weeks

I am trying to split a month into 4 weeks using perl.Say for eg. the input that I am giving a start date and end date. Start date-09/01/2014 End date-09/30/2014

perl should split the date range into 4 different weeks.Do you have any idea as how I proceed with that.

Thanks in advance..

Upvotes: 0

Views: 115

Answers (1)

Miller
Miller

Reputation: 35198

4 weeks lasts 28 days. You've prefaced your problem with a 30 day period.

Assuming you just want a week to stand for Sunday - Saturday, then the following code using Time::Piece would be of assistance to you:

use strict;
use warnings;

use Time::Piece;
use Time::Seconds;

my $start = '09/01/2014';
my $end   = '09/30/2014';
my $fmt   = '%m/%d/%Y';

# Normalized to Noon to avoid DST
my $week_start = Time::Piece->strptime( $start, $fmt ) + 12 * ONE_HOUR;
my $month_end  = Time::Piece->strptime( $end,   $fmt );

while (1) {
    print $week_start->strftime($fmt), ' - ';

    my $week_end = $week_start + ONE_DAY * ( 6 - $week_start->day_of_week );

    if ( $week_end > $month_end ) {
        print $end, "\n";
        last;
    }

    # Print End of Week and begin cycle for next week
    print $week_end->strftime($fmt), "\n";
    $week_start = $week_end + ONE_DAY;
}

Outputs:

09/01/2014 - 09/06/2014
09/07/2014 - 09/13/2014
09/14/2014 - 09/20/2014
09/21/2014 - 09/27/2014
09/28/2014 - 09/30/2014

Upvotes: 3

Related Questions