Gracefully get latest quarter date for a provided date in PHP
I have a script where I need to determine the latest date (YYYY-MM-DD) of a calendar quarter for a specific date. I am currently using the following code:
$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.');
}
The code works great, however it feels like something that should be achievable in just one or two lines. Is there a more graceful way to do this in PHP?
+3
source to share
3 answers
Assuming your date is valid, this should work fine.
list ($year, $month, $day) = explode('-', $dateProvided);
$month = $month % 3 ? $month + 3 - ($month % 3) : $month; //
$date = new Date();
$date->setDate($year, $month + 1, 0); //PHP will fix this date for you
echo $date->format('Y-m-d');
Hope it helps.
0
source to share
How about this code?
<?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.');
}
In an array, $last_day
you can store the remaining date, for example:
<?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.');
}
0
source to share
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));
0
source to share