Skip to content

Instantly share code, notes, and snippets.

@jehoshua02
Last active December 10, 2015 00:58
Show Gist options
  • Select an option

  • Save jehoshua02/4354601 to your computer and use it in GitHub Desktop.

Select an option

Save jehoshua02/4354601 to your computer and use it in GitHub Desktop.
<?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;
}
}
<?php
require __DIR__ . '/CalendarEvent.php';
$christmas = new CalendarEvent('christmas');
while (true) {
echo $christmas->timeUntilString() . "\n";
sleep(1);
}
@jehoshua02
Copy link
Author

Found a problem with timeUntilString() when the event is more than a month away.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment