I have a function that accepts ($year, $month = null, $day = null)
Essentially a year always has to be passed in, but the month and day are optional.
If they are not passed in then it sets the range to the biggest possible.
so: call | result
(2012, 08, 15) | ['2012-08-15', '2012-08-15']
(2012, 08) | ['2012-08-01', '2012-08-31']
(2012, 02) | ['2012-02-01', '2012-02-29']
(2012) | ['2012-01-01', '2012-12-31']
() | false
I have the below code, however to me it seems needlessly complex, can anyone think of a better version?
if (!is_null($year)) {
//year
$from = $year . '-';
$to = $year . '-';
//month
if (!is_null($month)) {
$from .= sprintf('%02d', $month) . '-';
$to .= sprintf('%02d', $month) . '-';
//day
if (!is_null($day)) {
$from .= sprintf('%02d', $day);
$to .= sprintf('%02d', $day);
} else {
$from .= '01';
$to .= sprintf('%02d', cal_days_in_month(CAL_GREGORIAN, $month, $year));
}
} else {
$from .= '01-31';
$to .= '12-31';
}
return array($from, $to);
}
return false;
First of all I would change the design a little so that the usage is more easy:
And then these helper functions:
I then might want to extract the differences between these two pretty similar looking functions and parametrice it but I am not sure.
If you prefer to have it within one function (and with a little different semantics resetting the
$dayif$monthis not set), this needs the branching with anif:This function would also not work if there will be one December in time which has less or more than 31 days.