问题描述:

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

网友答案:

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

print ((grep $_ <= $inputdate, sort @dates)[-1]);
网友答案:
use List::Util qw( max );
my $date = max grep { $_ <= $inputdate } @dates;
网友答案:

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
    }
}
相关阅读:
Top