2

如何使用输入日期从数组中获取早于输入日期或等于的最近日期?

例如,我的数组看起来像这样。

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

我的输入日期是

$inputdate = "201003";

如何获得数组中最接近的日期“200912”。

日期格式为 YEARMM。

谢谢

4

3 回答 3

4

对日期进行排序,仅选择输入日期之前的日期,取最后一个:

print ((grep $_ <= $inputdate, sort @dates)[-1]);
于 2013-06-19T07:37:32.963 回答
2
use List::Util qw( max );
my $date = max grep { $_ <= $inputdate } @dates;
于 2013-06-19T07:40:09.897 回答
-2

这里的逻辑是返回一年,如果月份是一月,则将月份从一月更改为十二月,否则在同一年返回一个月。

我在 Perl 中的代码不多,PHP 中的代码是:(我把它放在这里是为了给你逻辑。编码它应该是微不足道的)

$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
    }
}
于 2013-06-19T07:37:08.037 回答