Easily format ranges of dates
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 | |
/** | |
* @author Michael Bianco <http://mabblog.com> | |
* | |
**/ | |
class DateRange { | |
public $start; | |
public $end; | |
public function __construct($startDate, $endDate) { | |
// convert all date inputs into a datetime | |
if(is_a($startDate, "DateTime")) { | |
$this->start = $startDate; | |
} else if(is_string($startDate)) { | |
$this->start = new DateTime($startDate); | |
} else if(is_int($startDate)) { | |
$this->start = new DateTime("@{$startDate}"); | |
} | |
if(is_a($endDate, 'DateTime')) { | |
$this->end = $endDate; | |
} else if(is_string($endDate)) { | |
$this->end = new DateTime($endDate); | |
} else if(is_int($endDate)) { | |
$this->end = new DateTime("@{$endDate}"); | |
} else { | |
$this->end = $this->start; | |
} | |
} | |
public function isSingleDay() { | |
return $this->start->format('d') == $this->end->format('d'); | |
} | |
public function format($includeYear = TRUE, $includeSuffix = TRUE) { | |
$yearFormat = $includeYear ? ', Y' : ''; | |
$daySuffix = $includeSuffix ? 'S' : ''; | |
// n = month, d = day | |
if($this->start->format('n') == $this->end->format('n')) { | |
if($this->isSingleDay()) { | |
// July 7th, 2010 | |
return $this->start->format('F j'.$daySuffix.$yearFormat); | |
} else { | |
// July 7 - 10th, 2010 | |
return $this->start->format('F j').' - '.$this->end->format('j'.$daySuffix.$yearFormat); | |
} | |
} else { | |
return $this->start->format('F j'.$daySuffix.$yearFormat).' - '.$this->end->format('F j'.$daySuffix.$yearFormat); | |
} | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment