Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Perl how to find the date of the previous Monday for a given date?

Tags:

date

perl

I am looking for a Perl script which can give me the last Monday for any specified date.

e.g. For date 2011-06-11, the script should return 2011-06-06

like image 561
anilmwr Avatar asked Jun 07 '11 07:06

anilmwr


2 Answers

There are lot of ways to do it in Perl. Here is how it can be done with Perl library Moment.

#!/usr/bin/perl

use strict;
use warnings FATAL => 'all';
use feature 'say';

use Moment;

sub get_monday_date {
    my ($date) = @_;

    my $moment = Moment->new( dt => "$date 00:00:00" );

    my $weekday_number = $moment->get_weekday_number( first_day => 'monday' );

    my $monday = $moment->minus( day => ($weekday_number - 1) );

    return $monday->get_d();
}

say get_monday_date('2011-06-11'); # 2011-06-06
like image 80
bessarabov Avatar answered Nov 15 '22 10:11

bessarabov


Pretty simple stuff using the standard Perl library.

#!/usr/bin/perl

use strict;
use warnings;
use 5.010;

use Time::Local;
use POSIX 'strftime';

my $date = shift || die "No date given\n";

my @date = split /-/, $date;
$date[0] -= 1900;
$date[1]--;

die "Invalid date: $date\n" unless @date == 3;

my $now = timelocal(0, 0, 12, reverse @date);

while (strftime('%u', localtime $now) != 1) {
  $now -= 24 * 60 * 60;
}

I'll leave it as an exercise for the reader to look up the various modules and functions used.

It's probably even simpler if you use DateTime.

like image 21
Dave Cross Avatar answered Nov 15 '22 11:11

Dave Cross