Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Perl - How to get date of Previous wednesday from the given date without using DateTime

Tags:

date

unix

perl

All,

I want to find out the date of previous wednesday from the given date.

Eg. I have date as "20150804" and i would need "20150729".

DateTime is not available and i cannot install it as well.

I looked at few examples but they were using DateTime.

Can you please redirect me where i can get some help.? Thanks.

I am planning to code something like below.

Code:

#!/opt/perl-5.8.0/bin/perl

use warnings;
use strict;

my $dt="20150804";
my $prevWednesday=getPrevWednesday($dt);

sub getPrevWednesday()
{
    my $givenDt=shift;
    ...
}
like image 493
Mahesh Avatar asked Dec 19 '22 01:12

Mahesh


1 Answers

Another brute force approach, this time using another core module Time::Local.

#!/usr/bin/perl
use warnings;
use strict;

use Time::Local;

sub prev_wednesday {
    my $date = shift;
    my ($year, $month, $day) = $date =~ /(....)(..)(..)/;
    my $time = timelocal(0, 0, 12, $day, $month - 1, $year);
    do { $time -= 60 * 60 * 24 } until (localtime $time)[6] == 3; # <- Wednesday
    my ($y, $m, $d) = (localtime $time)[5, 4, 3];
    return sprintf "%4d%02d%02d\n", 1900 + $y, $m + 1, $d;
}

print $_, ' ', prev_wednesday($_), for qw( 20150804 20150805 20150806
                                           20150101 20000301 20010301 );
like image 60
choroba Avatar answered May 24 '23 08:05

choroba