user2285115
user2285115

Reputation: 77

Perl find closest date in array

How do I get the closest date that is earlier than the input date or equal to from an array using an input date?

For example, my array would look like this.

@dates = ("200811","200905","200912","201005","201202");

and my input date is

$inputdate = "201003";

How do I get the closest date in the array which is "200912".

The format of the date is YEARMM.

Thanks

Upvotes: 2

Views: 811

Answers (3)

Rishi Dua
Rishi Dua

Reputation: 2334

The logic here is to go one year back and change month from January to December if the month is January, otherwise go back one month in the same year.

I don't code much in Perl, the code in PHP is: (I'm putting it here to give you the logic. Coding it should be trivial)

$dates = array("200811","200905","200912","201005","201202");
$inputdate = "201003";
$date = $inputdate;
while ($found==0) {
    if (in_array($date, $dates)) {
        $found = 1;
        echo "the date is " . $date;
    }
    if ($date%100==1) { // if it's january, we need to change to december of the previous year
        $date = $date - 100 + 12;
    }
    else  {
        $date = $date - 1; //go one month back in the same year
    }
}

Upvotes: -2

stevenl
stevenl

Reputation: 6798

use List::Util qw( max );
my $date = max grep { $_ <= $inputdate } @dates;

Upvotes: 2

choroba
choroba

Reputation: 241908

Sort the dates, select only the ones preceding the input date, take the last such one:

print ((grep $_ <= $inputdate, sort @dates)[-1]);

Upvotes: 4

Related Questions