read

I recently came across PHP’s DateTime object and I’m loving it.

// Calculate month and year to look for
$month = !empty($_GET['month']) ? $_GET['month'] : date('m');
$year = !empty($_GET['year']) ? $_GET['year'] : date('Y');

// Start of the month
$start_date = new DateTime($year.'-'.$month.'-01');

// End of the month
$end_date = new DateTime( $start_date->format('Y-m-d') );
$end_date->modify('+1 month -1 day');

echo ' Start: '. $start_date->format('d m Y');
echo ' End: '. $end_date->format('d m Y');

Working out the first Monday of the month is also quite easy, but has one slight complication. If Monday is on the 1st, the modifier “first monday” will look for the next Monday AFTER that, meaning the 8th.

$first_monday = new DateTime($start_date->format('Y-m-d'));
if($first_monday->format('l') != 'Monday') $first_monday->modify('first monday');

DateTime may have been around for a while now, but it’s still not fully documented or even entirely complete on any of the PHP set-ups I have tried it on. Still waiting on DateTime::diff().

Blog Logo

Phil Sturgeon

Phil has contributed to CodeIgniter, FuelPHP, Laravel and handfuls of other projects, to try and make the PHP community a better place.


Published

Build APIs You Won't Hate

Everyone and their dog wants an API, so you should probably learn how to build them.

Buy it from LeanPub for $26.99


Published 01 Feb 2014

Image

Phil Sturgeon

Founder of PyroCMS, Senior Developer at Ride, Programming Polyglot, PHP-FIG member, and occasionally gets chased by bears

Back to Overview