Created
March 25, 2012 16:26
-
-
Save colindecarlo/2198044 to your computer and use it in GitHub Desktop.
Calculate the last <blank> of the month
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
class MyDateTime extends DateTime | |
{ | |
protected $_daysOfTheWeek = array('sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'); | |
public function lastDayOfTheMonth() | |
{ | |
$lastDayOfTheMonth = new MyDateTime($this->format('Y-m-t'), $this->getTimezone()); | |
return $lastDayOfTheMonth; | |
} | |
public function lastWeekdayOfTheMonth($weekday) | |
{ | |
if (false === ($weekdayIndex = array_search(strtolower($weekday), $this->_daysOfTheWeek))) { | |
throw new Exception("Unknown weekday: " . $weekday); | |
} | |
$lastDayOfTheMonth = $this->lastDayOfTheMonth(); | |
$lastWeekday = clone $lastDayOfTheMonth; | |
if ($lastDayOfTheMonth->format('w') < $weekdayIndex) { | |
$lastWeekday->sub(new DateInterval('P7D')); | |
$daysUntil = $weekdayIndex - $lastDayOfTheMonth->format('w'); | |
$lastWeekday->add(new DateInterval(sprintf('P%dD', $daysUntil))); | |
} else if ($lastDayOfTheMonth->format('w') > $weekdayIndex) { | |
$daysSince = $lastDayOfTheMonth->format('w') - $weekdayIndex; | |
$lastWeekday->sub(new DateInterval(sprintf("P%dD", $daysSince))); | |
} | |
return $lastWeekday; | |
} | |
} | |
$today = new MyDateTime(null, new DateTimeZone('America/Toronto')); | |
$lastWednesday = $today->lastWeekdayOfTheMonth('wednesday'); | |
echo $lastWednesday->format('Y-m-d') . "\n"; | |
$april = new MyDateTime('2012-04-01', new DateTimeZone('America/Toronto')); | |
$lastWednesday = $april->lastWeekdayOfTheMonth('wednesday'); | |
echo $lastWednesday->format('Y-m-d') . "\n"; | |
$october = new MyDateTime('2012-10-01', new DateTimeZone('America/Toronto')); | |
$lastWednesday = $october->lastWeekdayOfTheMonth('wednesday'); | |
echo $lastWednesday->format('Y-m-d') . "\n"; | |
$september = new MyDateTime('2012-09-01', new DateTimeZone('America/Toronto')); | |
$lastSunday = $september->lastWeekdayOfTheMonth('sunday'); | |
echo $lastSunday->format('Y-m-d') . "\n"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fair enough-I understand where you're coming from. I'll just keep performing my black magic. :)