如何使用输入日期从数组中获取早于或等于输入日期的最近日期?
例如,我的数组看起来像这样。
@dates = ("200811","200905","200912","201005","201202");我的输入日期是
$inputdate = "201003";如何获取数组中最接近的日期"200912“?
日期的格式为YEARMM。
谢谢
发布于 2013-06-19 15:37:33
对日期进行排序,只选择输入日期之前的日期,取最后一个日期:
print ((grep $_ <= $inputdate, sort @dates)[-1]);发布于 2013-06-19 15:40:10
use List::Util qw( max );
my $date = max grep { $_ <= $inputdate } @dates;发布于 2013-06-19 15:37:08
这里的逻辑是返回一年,如果月份是1月,则将月份从1月更改为12月,否则返回同年的一个月。
我用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
}
}https://stackoverflow.com/questions/17185169
复制相似问题