优雅地获取PHP中提供日期的季度的最后日期

时间:2014-11-10 12:25:13

标签: php date

我有一个脚本,我需要确定给定日期的日历季度的最后日期(YYYY-MM-DD)。目前我使用的代码如下:

$dateProvided = '2014-12-21';
list ($year, $month, $day) = explode('-', $dateProvided);               
if ($month <= 3) {
    return date('Y', strtotime($dateProvided)).'-03-31';                        
} elseif ($month <= 6) {
    return date('Y', strtotime($dateProvided)).'-06-30';                        
} elseif ($month <= 9) {
    return date('Y', strtotime($dateProvided)).'-09-30';                        
} elseif ($month <= 12) {
    return date('Y', strtotime($dateProvided)).'-12-31';                        
} else {
    throw new OutOfRangeException('Month '.$month.' is invalid.');
}

代码工作正常,但感觉就像只需要一两行即可实现。在PHP中有更优雅的方法吗?

4 个答案:

答案 0 :(得分:1)

假设您的日期有效,这应该可以正常工作。

$dateProvided = '2019-02-28';
list ($year, $month, $day) = explode('-', $dateProvided);
$month = $month % 3 ? $month + 3 - ($month % 3) : $month;
$date = new DateTime();
$date->setDate($year, $month + 1, 0); //PHP will fix this date for you 
echo $date->format('Y-m-d');

希望它有所帮助。

答案 1 :(得分:0)

这段代码怎么样?

<?php

$dateProvided = '2014-07-21';
list ($year, $month, $day) = explode('-', $dateProvided);

$last_day = array(1 => 31, 30, 30, 31); // last date in 3rd, 6th, 9th, 12th month
$quarter = ceil($month / 3); // returns 1-4

if ($month >= 1 && $month <= 12) {
    echo $year . '-' . (3 * $quarter) . '-' . str_pad($last_day[$quarter], 2, '0', STR_PAD_LEFT);
} else {
    throw new OutOfRangeException('Month '.$month.' is invalid.');
}

$last_day数组中,您可以存储剩下的日期,如:

<?php

$dateProvided = '2014-04-21';
list ($year, $month, $day) = explode('-', $dateProvided);

$last_day = array(1 => '03-31', '06-30', '09-30', '12-31');
$quarter = ceil($month / 3); // returns 1-4

if ($month >= 1 && $month <= 12) {
    echo $year . '-' . $last_day[$quarter];
} else {
    throw new OutOfRangeException('Month '.$month.' is invalid.');
}

答案 2 :(得分:0)

function getMonth($month)
{
    if($month % 3 > 0)
    {
        return getMonth($month+1);
    }

    return $month;
}

$dateProvided = '2014-9-21';
list ($year, $month, $day) = explode('-', $dateProvided);
$qtMonth = getMonth($month);
$dateResult = sprintf('2014-%d-%d', 
                            $qtMonth, 
                            (in_array($qtMonth, array(6,9)) ? 30 : 31));

答案 3 :(得分:0)

如果有人只需要使用两行:

$dateProvided = '2014-02-21';
list ($year, $month, $day) = explode('-', $dateProvided);
return date('Y-m-t', strtotime($year. '-'. ($month  =  ($month > 9 ? '' : '0') . ceil($month /3) * 3 ) . '-' . $day));