Last active
December 10, 2015 00:58
-
-
Save jehoshua02/4354601 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 | |
| class CalendarEvent | |
| { | |
| /** | |
| * Holds the event | |
| * | |
| * @var string | |
| */ | |
| protected $event; | |
| /** | |
| * Constants representing calendar event strings | |
| * | |
| * @var string | |
| */ | |
| const EVENT_CHRISTMAS = 'christmas'; | |
| /** | |
| * Construct method | |
| * | |
| * @param string $event | |
| */ | |
| public function __construct($event) | |
| { | |
| $this->event = $event; | |
| } | |
| /** | |
| * Calculates time until event | |
| * | |
| * @return DateInterval | |
| */ | |
| public function timeUntil() | |
| { | |
| $now = new DateTime(); | |
| $eventDate = $this->toDateTime(); | |
| return $eventDate->diff($now); | |
| } | |
| /** | |
| * Calculates time until event formatted as string | |
| * | |
| * @param string $format | |
| * @see http://php.net/manual/en/dateinterval.format.php | |
| * | |
| * @return string | |
| */ | |
| public function timeUntilString($format = '%d days, %h hours, %i minutes, %s seconds') | |
| { | |
| return $this->timeUntil()->format($format); | |
| } | |
| /** | |
| * Converts CalendarEvent object to DateTime object | |
| * | |
| * @return DateTime | |
| */ | |
| public function toDateTime() | |
| { | |
| $now = new DateTime(); | |
| switch ($this->event) { | |
| case self::EVENT_CHRISTMAS: | |
| $eventDate = new DateTime(date('Y-m-d H:i:s', mktime(0, 0, 0, 12, 25, date('Y')))); | |
| if ($now > $eventDate) { | |
| $eventDate->add(new DateInterval('P1Y')); | |
| } | |
| break; | |
| } | |
| return $eventDate; | |
| } | |
| } | |
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 | |
| require __DIR__ . '/CalendarEvent.php'; | |
| $christmas = new CalendarEvent('christmas'); | |
| while (true) { | |
| echo $christmas->timeUntilString() . "\n"; | |
| sleep(1); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Found a problem with timeUntilString() when the event is more than a month away.