I have an action which accepts a year and an optional month. I need to query all articles written within that time, so I need the absolute first and last valid datetime for that timespan.
$start = new \DateTime();
$start->setDate((int) $year, (int) ($month ?: 1), 1);
$start->setTime(0, 0);
$end = clone $start;
$end->add(new \DateInterval($month ? 'P1M' : 'P1Y'));
$end->sub(new \DateInterval('PT1S'));
Is there a cleaner way to write this?
or
Not sure if you’d consider this cleaner, but it’s shorter and does without relative calculations.
The cleanest and most understandable way to write this is probably:
You might not need to involve
DateTimemuch at all here if you’re going to use this as value for an SQL query.