Created
March 23, 2011 21:35
-
-
Save caefer/884067 to your computer and use it in GitHub Desktop.
This file contains hidden or 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 | |
| namespace Caefer; | |
| class WeekAhead extends \DateTime | |
| { | |
| protected $terms = array( | |
| 'today' => 'now', | |
| 'tomorrow' => '+1 days', | |
| ); | |
| protected $weekdays = array('Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'); | |
| public function __construct($time = 'now', $timezone = null) | |
| { | |
| if (isset($this->terms[$time])) { | |
| $time = $this->terms[$time]; | |
| } | |
| if (in_array($time, $this->weekdays)) { | |
| $time = sprintf('+%d days', (array_search($time, $this->weekdays) - date('N') + 8) % 7); | |
| } | |
| // necessary as passing null will throw exception! | |
| if (is_null($timezone)) { | |
| parent::__construct($time); | |
| } else { | |
| parent::__construct($time, $timezone); | |
| } | |
| } | |
| public function format($format) | |
| { | |
| $formatted = parent::format($format); | |
| if (false !== strpos($format, 'X')) { | |
| $today = new \DateTime(); | |
| $diff = (int) $today->diff($this)->format('%a'); | |
| switch ($diff) { | |
| case 0: | |
| $ahead = $this->terms[0]; | |
| break; | |
| case 1: | |
| $ahead = $this->terms[1]; | |
| break; | |
| case 2: | |
| case 3: | |
| case 4: | |
| case 5: | |
| case 6: | |
| $ahead = $this->weekdays[(date('N') + $diff - 1) % 7]; | |
| break; | |
| default: | |
| return false; | |
| } | |
| $formatted = str_replace('X', $ahead, $formatted); | |
| } | |
| return $formatted; | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment