Skip to content

Instantly share code, notes, and snippets.

@iloveitaly
Created July 6, 2010 14:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save iloveitaly/465427 to your computer and use it in GitHub Desktop.
Easily format ranges of dates
<?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