Created
October 17, 2020 22:32
-
-
Save leonardola/e269a884bc151c1e38d853d8f0424929 to your computer and use it in GitHub Desktop.
How to create a calendar in php
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 | |
class Calendar | |
{ | |
private $month; | |
private $date; | |
private $events = []; | |
public function __construct($date) | |
{ | |
$this->date = new \DateTime($date); | |
$this->month = $this->getMonth(); | |
$this->setFirstDay(); | |
} | |
public function next() | |
{ | |
return $this->date->modify("+ 1 day"); | |
} | |
public function getDay() | |
{ | |
return $this->date->format("j"); | |
} | |
public function isCurrentMonth() | |
{ | |
return $this->date->format("n") == $this->month; | |
} | |
public function addEvent($day, $data) | |
{ | |
$this->events[$day][] = $data; | |
} | |
public function getEvents() | |
{ | |
//only shows events of the current month | |
if (!isset($this->events[$this->getDay()]) || !$this->isCurrentMonth()) { | |
return []; | |
} | |
return $this->events[$this->getDay()]; | |
} | |
private function getMonth() | |
{ | |
return $this->date->format("n"); | |
} | |
/* | |
* sets the initial date as the first Monday of the calendar(usually not the first day of the current month but the last days of the previous month) | |
*/ | |
private function setFirstDay() | |
{ | |
$this->date->modify('first day of this month'); | |
$firstWeekDay = $this->getFirstWeekDay(); | |
$this->date->modify("-{$firstWeekDay} days"); | |
} | |
/* | |
* weekday (0 for Sunday) | |
*/ | |
private function getFirstWeekDay() | |
{ | |
return $this->date->format("w"); | |
} | |
} | |
$calendar = new Calendar($_GET['date']); | |
$event = [ | |
'name' => "Take a nap", | |
'date' => '16/10/2020', | |
'time' => '14:00', | |
]; | |
$calendar->addEvent(1, $event); | |
$event = [ | |
'name' => "Wakeup", | |
'date' => '16/10/2020', | |
'time' => '15:00', | |
]; | |
$calendar->addEvent(1, $event); | |
?> | |
<table border="1"> | |
<thead> | |
<tr> | |
<th>D</th> | |
<th>S</th> | |
<th>T</th> | |
<th>Q</th> | |
<th>Q</th> | |
<th>S</th> | |
<th>S</th> | |
</tr> | |
</thead> | |
<?php for ($week = 0; $week < 6; $week++) { ?> | |
<tr> | |
<?php for ($day = 0; $day < 7; $day++) { ?> | |
<?php $date = $calendar->next() ?> | |
<td <?php if (!$calendar->isCurrentMonth()) { ?> style="background: gray" <?php } ?>> | |
<?= $calendar->getDay() ?> | |
<?php foreach ($calendar->getEvents() as $event) { ?> | |
<div><?= $event['name'] ?></div> | |
<?php } ?> | |
</td> | |
<?php } ?> | |
</tr> | |
<?php } ?> | |
</table> | |
<?php | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment