Skip to content

Instantly share code, notes, and snippets.

@mgirouard
Created October 5, 2010 21:05
Show Gist options
  • Save mgirouard/612334 to your computer and use it in GitHub Desktop.
Save mgirouard/612334 to your computer and use it in GitHub Desktop.
<?php
class Calendar
{
protected $date;
public $timezone = 'America/New_York';
public $yearFormat = 'Y';
public $monthFormat = 'n';
public $dayFormat = 'd';
public function __construct ($date)
{
$this->setTimezone($this->timezone);
$this->setDate($date);
}
public function setTimezone($timezone)
{
date_default_timezone_set($timezone);
}
public function getDate($format = null)
{
if ($format === null) {
return $this->date;
}
else {
return date($format, $this->date);
}
}
public function setDate($date)
{
$this->date = strtotime($date);
}
public function getYear($format = 'Y')
{
return $this->getDate($this->yearFormat);
}
public function setYear($year)
{
$this->setDate(sprintf(
'%s-%s-%s',
(int) $year, $this->getMonth(), $this->getDay()
));
}
public function getMonth()
{
return $this->getDate($this->monthFormat);
}
public function setMonth($month)
{
$this->setDate(sprintf(
'%s-%s-%s',
$this->getYear(), (int) $month, $this->getDay()
));
}
public function getDay()
{
return $this->getDate($this->dayFormat);
}
public function setDay($day)
{
$this->setDate(sprintf(
'%s-%s-%s',
$this->getYear(), $this->getMonth(), (int) $day
));
}
public function getCalendar()
{
$out = array();
$month = $this->getMonth();
$year = $this->getYear();
$count = self::countDaysInMonth($month, $year);
$offset = self::monthStartOffset($month, $year);
$wom = 1;
$dow = 1;
for ($i = 1; $i <= $count + $offset; $i++) {
$day = $i - $offset;
if ($dow > 7) {
$wom += 1;
$dow = 1;
}
if (empty($out[$wom])) {
$out[$wom] = array();
}
$out[$wom][$dow] = $day;
$dow++;
}
return $out;
}
public static function countDaysInMonth($month, $year)
{
// Fixme: This is awful.
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
public static function monthStartOffset($month, $year)
{
return (int) date('w', mktime(0, 0, 0, $month, 1, $year));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment