Want to show Date, Time and Hours?
please help me to find out how to modify this code now its showing hours ago and days ago...
Screen Shot
enter code here
abstract class Rss_Model_Feed_Abstract extends Core_Model_Default {
protected $_news = array();
protected function _parse() {
$feed = Zend_Feed_Reader::import($this->getLink());
$this->_news = new Core_Model_Default(array(
'title' => $feed->getTitle(),
'link' => $feed->getLink(),
'dateModified' => $feed->getDateModified(),
'description' => $feed->getDescription(),
'language' => $feed->getLanguage(),
'entries' => array(),
));
$data = array();
foreach ($feed as $entry) {
$picture = null;
if($entry->getEnclosure() && $entry->getEnclosure()->url) $picture = $entry->getEnclosure()->url;
$description = "";
if($entry->getContent()) {
$content = new Dom_SmartDOMDocument();
$content->loadHTML($entry->getContent());
$content->encoding = 'utf-8';
$description = $content->documentElement;
$imgs = $description->getElementsByTagName('img');
if($imgs->length > 0) {
foreach($imgs as $k => $img) {
if($k == 0) {
$img = $imgs->item(0);
if($img->getAttribute('src') AND stripos($img->getAttribute('src'), ".gif") === false) {
$picture = $img->getAttribute('src');
$img->parentNode->removeChild($img);
}
}
$img->removeAttribute('width');
$img->removeAttribute('height');
}
}
$as = $description->getElementsByTagName('a');
if($as->length > 0) {
foreach($as as $a) {
$a->setAttribute('target', '_self');
}
}
$description = $content->saveHTMLExact();
}
$timestamp = $entry->getDateCreated() ? $entry->getDateCreated()->getTimestamp() : null;
$updated_at = null;
if($timestamp) {
$updated_at = $this->_getUpdatedAt($timestamp);
}
$edata = new Core_Model_Default(array(
'entry_id' => $entry->getId(),
'title' => $entry->getTitle(),
'description' => $description,
'short_description' => strip_tags($description),
'dateModified' => $entry->getDateModified(),
'authors' => $entry->getAuthors(),
'link' => $entry->getLink(),
'content' => $description,
'enclosure' => $entry->getEnclosure(),
'timestamp' => $timestamp,
'updated_at' => $updated_at,
'picture' => $picture,
));
$data[] = $edata;
}
$this->_news->setEntries($data);
return $this;
}
protected function _getUpdatedAt($timestamp) {
$date = new Zend_Date($timestamp);
$now = Zend_Date::now();
$difference = $now->sub($date);
$seconds = $difference->toValue() % 60; $allMinutes = ($difference->toValue() - $seconds) / 60;
$minutes = $allMinutes % 60; $allHours = ($allMinutes - $minutes) / 60;
$hours = $allHours % 24; $days = ($allHours - $hours) / 24;
switch($days) {
case 0: $days = false; break;
case 1: $days .= " {$this->_('day')}"; break;
default: $days .= " {$this->_('days')}"; break;
}
switch($hours) {
case 0: $hours = false; break;
case 1: $hours .= " {$this->_('hour')}"; break;
default: $hours .= " {$this->_('hours')}"; break;
}
switch($minutes) {
case 0: $minutes = false; break;
case 1: $minutes .= " {$this->_('minute')}"; break;
default: $minutes .= " {$this->_('minutes')}"; break;
}
switch($seconds) {
case 0: $seconds = false; break;
case 1: $seconds .= " {$this->_('second')}"; break;
default: $seconds .= " {$this->_('seconds')}"; break;
}
$updated_at = '';
if($days) {
$updated_at = $days;
} elseif($hours) {
$updated_at = $hours;
} elseif($minutes) {
$updated_at = $minutes;
} elseif($seconds) {
$updated_at = $seconds;
}
return $this->_('%s ago', $updated_at);
}
}
Hello I think you ask time date formatting
// to show both date and time,
$date->get('YYYY-MM-dd HH:mm:ss');
// or, to show date only
$date->get('YYYY-MM-dd')
this will help to get time and date
I'm going to trust the naming i see in your code and assume the $timestamp is really a time stamp :)
In which case all you need is to format it in a desired shape using the PHP's date method, in other word you wont need the _getUpdatedAt method in your code.
so you have to change:
$timestamp = $entry->getDateCreated() ? $entry->getDateCreated()->getTimestamp() : null;
$updated_at = null;
if($timestamp) {
$updated_at = $this->_getUpdatedAt($timestamp);
}
to
$timestamp = $entry->getDateCreated() ? $entry->getDateCreated()->getTimestamp() : null;
$updated_at = date('Y-m-d H:i:s', $timestamp);
In the above example the displayDate will be something like 2015-09-28 10:34:56 which you can modify by amending the date's method first parameter 'Y-m-d H:i:s'
Related
I am trying to create an array using PHP OOP that basically creates and array for every day, month, year within 2 dates and allocates a ticket and hours worked set at 0 for every single day that has passed.
The code I have used is:
class statisticsClass{
private $DateFrom = null;
private $DateTo = null;
private $startYear = null;
private $startMonth = null;
private $startDay = null;
private $endYear = null;
private $endMonth = null;
private $endDay = null;
private $theDateDif = null;
private $stages = null;
private function makeDates(){
if(!empty($this->DateFrom)){
$this->DateFrom = $this->generals->convertDate($this->DateFrom);
} else {
$this->DateFrom = date('Y-m-d', strtotime('last year')) . ' 00:00:00';
}
if(!empty($this->DateTo)){
$this->DateTo = $this->generals->convertDate($this->DateTo);
} else {
$this->DateTo = date('Y-m-d', strtotime('now')) . ' 23:59:59';
}
list($theDate, $theTime) = explode(' ', $this->DateFrom);
list($this->startYear, $this->startMonth, $this->startDay) = explode('-', $theDate);
list($theDate2, $theTime2) = explode(' ', $this->DateTo);
list($this->endYear, $this->endMonth, $this->endDay) = explode('-', $theDate2);
}
private function removeZeros($number){
return ltrim($number, '0');
}
private function chartItemVersion(){
if($this->theDateDif <= 31){
$this->stages = 'daily';
} elseif($this->theDateDif > 31 && $this->theDateDif <= 183){
$this->stages = 'weekly';
} else {
$this->stages = 'monthly';
}
}
private function addZeros($number){
if($number < 10){
return '0' . $number;
}
return $number;
}
private function makingQueryArray(){
for($yearMake=$this->startYear; $yearMake<=$this->endYear; $yearMake++){
$this->queryArray[] = intval($yearMake);
}
foreach($this->queryArray as $year){
if($year === $this->startYear){
$currentMonth = intval($this->removeZeros($this->startMonth));
for($currentMonth; $currentMonth <= 12;$currentMonth++){
$this->queryArray[$year][] = (string)$this->addZeros($currentMonth);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($currentMonth), $year);
if($this->startYear === $this->addZeros($currentMonth)){
$currentDay = intval($this->removeZeros($this->startDay));
for($currentDay; $currentDay <= $tempHowManyDays; $currentDay){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($currentDay)]['Hours'] = 0;
}
} else {
for($i=1; $i<=$tempHowManyDays; $i++){
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($currentMonth)][(string)$this->addZeros($i)]['Hours'] = 0;
}
}
}
} elseif($year === $this->endYear) {
$endMonth = intval($this->removeZeros($this->endMonth));
for($a=1; $a <= $endMonth; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
if($a === $endMonth){
$tempHowManyDays = intval($this->removeZeros($this->endDay));
} else {
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
}
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
} else {
for($a=1; $a <= 12; $a++){
$this->queryArray[$year][] = (string)$this->addZeros($a);
$tempHowManyDays = cal_days_in_month(CAL_GREGORIAN, $this->addZeros($a), $year);
for($b=1; $b<=$tempHowManyDays; $b++){
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['ticket'] = 0;
$this->queryArray[$year][(string)$this->addZeros($a)][(string)$this->addZeros($b)]['Hours'] = 0;
}
}
}
}
var_dump($this->queryArray);
}
private function dateDifference(){
$now = strtotime($this->DateFrom);
$your_date = strtotime($this->DateTo);
$datediff = $your_date - $now;
$this->theDateDif = round($datediff / (60 * 60 * 24));
}
function __construct($pdo, $theArray, $generals = null){
if($generals !== null){ $this->generals = $generals; }
$this->pdo = $pdo;
if(isset($theArray['DateFrom']) && !empty($theArray['DateFrom'])){ $this->DateFrom = $theArray['DateFrom']; }
if(isset($theArray['DateTo']) && !empty($theArray['DateTo'])){ $this->DateTo = $theArray['DateTo']; }
$this->makeDates();
$this->dateDifference();
$this->chartItemVersion();
$this->makingQueryArray();
var_dump($this->queryArray);
}
}
$theArray = array();
$amhStatistics = new statisticsClass($pdo, $theArray, $generals);
I have been playing around with it for a while and can not get this array to function corectly.
The array should look like this:
array(){
'2018' => array(
01 => array(
01 => array(
'ticket' => 0,
'hours' => 0,
),
02 => array(
'ticket' => 0,
'hours' => 0,
)
)
)
}
As stated the only stipulation is that the start date should start at the start date and the end date should start at the end date.
Could someone point me in the right direction.
Cheers.
Your makingQueryArray function seems complicate - I believe you should solve it differently.
You can use dateperiod to get all days between 2 dates:
$startDate = '2010-10-01';
$endDate = '2010-10-05';
$period = new DatePeriod(new DateTime($startDate), new DateInterval('P1D'), new DateTime($endDate));
Now You can loop on all days and set you array:
foreach ($period as $key => $value) {
$d = explode("-", $value->format('Y-m-d'));
$res[$d[0]][$d[1]][$d[2]] = array('ticket' => 0, 'hours' => 0);
}
$res will give you your desire output. Live example: 3v4l
I have a problem to show the list time.
I saved start time, end time, interval time and block time in mysql.
e.g.
for start time : 09:00
for end time : 15:00
interval : 3
block time : 10:00-11:00;13:00-14:00
static function getListTime($time_interval,$s_hour, $e_hour, $peakTimesConfig){
switch ($time_interval) {
case '1':
$interval = new DateInterval('PT15M');
break;
case '2':
$interval = new DateInterval('PT30M');
break;
case '3':
$interval = new DateInterval('PT1H');
break;
case '4':
$interval = new DateInterval('PT2H');
break;
}
$result = array();
$time = new DateTime($s_hour);
$eTime = new DateTime($e_hour);
$bookingTimeIntervalSecond = $time_interval * 60;
$unavaibaleTimes = explode(';', $peakTimesConfig);
$arrUnavaibaleTimes = [];
foreach ($unavaibaleTimes as $unavaibaleTime) {
$strTime = explode('-', $unavaibaleTime);
$startTime = strtotime($strTime[0]);
if (!isset($strTime[1])) {
$endTime = $startTime + $bookingTimeIntervalSecond;
} else {
$endTime = strtotime($strTime[1]);
}
$arrUnavaibaleTimes[]=['startTime'=>$startTime,'endTime' => $endTime];
}
//sorting
for($i = 0; $i < count($arrUnavaibaleTimes); $i ++) {
for($j = 0; $j < count($arrUnavaibaleTimes); $j ++) {
if ($arrUnavaibaleTimes[$i]['startTime'] < $arrUnavaibaleTimes[$j]['startTime']) {
$sorting = $arrUnavaibaleTimes[$i];
$arrUnavaibaleTimes[$i] = $arrUnavaibaleTimes[$j];
$arrUnavaibaleTimes[$j]= $sorting;
}
}
}
$i = 0;
while ($time < $eTime) {
foreach($arrUnavaibaleTimes as $times){
if ($time->getTimestamp() < $times['startTime'] || $time->getTimestamp() >= $times['endTime']) {
if(!in_array($time->format("H:i"), $result)){
$result[] = $time->format("H:i");
}
}
else{
break;
}
}
$time->add($interval);
$i++;
}
return $result;
}
My question is : I want to show time slot from start time to end time without the block time.
e.g.
result : 09:00, 11:00, 12:00, 14:00, 15:00
Personally, I would do this with a class with something like the following. Note: Very little error checking on the data. You would need to test for garbage input.
The following class will display:
09:00, 11:00, 12:00, 14:00, 15:00
Changing the start value to 09:15 would currently render the following which may not be the result you want, but it is what I would want:
09:15, 11:00, 12:00, 14:00, 15:00
And changing start to 10:00 renders:
11:00, 12:00, 14:00, 15:00
And one final test, changing interval to 2:
09:00, 09:30, 11:00, 11:30, 12:00, 12:30, 14:00, 14:30, 15:00
The code:
// This would be from your mysql.
$raw = array(
'start'=>'09:00',
'end'=>'15:00',
'interval'=>3,
'block'=>'10:00-11:00;13:00-14:00'
);
$ts = new TimeSlot($raw);
echo 'Result: '.$ts->result();
// Note: Very little error checking on the input data!
class TimeSlot {
private $interval = 60;
private $block = null;
private $start = null;
private $end = null;
public function __construct($data=null) {
if ($data) {
if ($data['interval']) {
$this->setInterval($data['interval']);
}
if ($data['block']) {
$this->setBlock($data['block']);
}
if ($data['start']) {
$this->setStart($data['start']);
}
if ($data['end']) {
$this->setEnd($data['end']);
}
}
}
public function result() {
$result = null;
if (($this->start) && ($this->end)) {
$t = explode(':',$this->start);
$hs = $t[0];
$ms = $t[1];
do {
$t = $hs.':'.str_pad($ms,2,'0');
if (! $this->block[$t]) {
$result .= $t.', ';
}
$ms += $this->interval;
if ($ms >= 60) {
$ms = 0;
$hs++;
}
} while($t != $this->end);
}
return (strlen($result) > 5) ? substr($result,0,-2) : $result;
}
private function setInterval($interval) {
switch($interval) {
case 1:
$this->interval = 15;
break;
case 2:
$this->interval = 30;
break;
case 4:
// you would need to code for this option
$this->interval = 120;
break;
default:
$this->interval = 60;
}
}
private function setBlock($block) {
if ($block) {
$tmp = explode(';',$block);
foreach($tmp as $k=>$v) {
$b = explode('-',$v);
if (is_array($b)){
$ts = explode(':',$b[0]);
$hs = $ts[0];
$ms = $ts[1];
$n = $b[0];
do {
$t = $n;
$this->block[$t] = $t;
$ms += 15;
if ($ms >= 60) {
$ms = 0;
$hs++;
}
$n = $hs.':'.str_pad($ms,2,'0');
} while ($n != $b[1]);
}
}
}
}
// no error check at all!
private function setStart($start) {
$this->start = $start;
}
// no error check at all!
private function setEnd($end) {
$this->end = $end;
}
}
I have a php function to calculate timestamp (start date) to current (end) date that will return 1hr 30min 2s format. What I want to achieve is to calculate only from 8AM to 5PM of a working day. Anything that goes beyond will not be counted. Here is the php code I have.
class duration_computation {
function duration( $time ) {
$d[0] = array(1, "s");
$d[1] = array(60, "min");
$d[2] = array(3600, "hr");
$d[3] = array(86400, "dy");
$d[4] = array(604800, "wk");
$d[5] = array(2592000, "mth");
$d[6] = array(31104000, "yr");
$numbers = array();
$result = "";
$now = time();
$time_difference = ( $now - $time );
$seconds_left = $time_difference;
for ( $i = 6; $i > -1; $i-- ) {
$numbers[$i] = intval( $seconds_left / $d[$i][0] );
$seconds_left -= ( $numbers[$i] * $d[$i][0] );
if ( $numbers[$i] != 0 ) {
$result.= abs($numbers[$i]) . "" . $d[$i][1] . (($numbers[$i]>1)?'':'') ." ";
}
}
return $result;
}
}
$duration = new duration_computation();
echo $duration->duration($trail->duration);
Forget about date(), strtotime(), time(), etc. function, use DateTime :
Use example :
$from = '2013-09-06 15:45:32';
$to = '2013-09-14 21:00:00';
echo some_func_name($from, $to);
Output :
1 day, 22 hours, 14 minutes, 28 seconds
Function :
function some_func_name($from, $to) {
$workingDays = [1, 2, 3, 4, 5]; # date format = N
$workingHours = ['from' => ['08', '00'], 'to' => ['17', '00']];
$start = new DateTime($from);
$end = new DateTime($to);
$startP = clone $start;
$startP->setTime(0, 0, 0);
$endP = clone $end;
$endP->setTime(23, 59, 59);
$interval = new DateInterval('P1D');
$periods = new DatePeriod($startP, $interval, $endP);
$sum = [];
foreach ($periods as $i => $period) {
if (!in_array($period->format('N'), $workingDays)) continue;
$startT = clone $period;
$startT->setTime($workingHours['from'][0], $workingHours['from'][1]);
if (!$i && $start->diff($startT)->invert) $startT = $start;
$endT = clone $period;
$endT->setTime($workingHours['to'][0], $workingHours['to'][1]);
if (!$end->diff($endT)->invert) $endT = $end;
#echo $startT->format('Y-m-d H:i') . ' - ' . $endT->format('Y-m-d H:i') . "\n"; # debug
$diff = $startT->diff($endT);
if ($diff->invert) continue;
foreach ($diff as $k => $v) {
if (!isset($sum[$k])) $sum[$k] = 0;
$sum[$k] += $v;
}
}
if (!$sum) return 'ccc, no time on job?';
$spec = "P{$sum['y']}Y{$sum['m']}M{$sum['d']}DT{$sum['h']}H{$sum['i']}M{$sum['s']}S";
$interval = new DateInterval($spec);
$startS = new DateTime;
$endS = clone $startS;
$endS->sub($interval);
$diff = $endS->diff($startS);
$labels = [
'y' => 'year',
'm' => 'month',
'd' => 'day',
'h' => 'hour',
'i' => 'minute',
's' => 'second',
];
$return = [];
foreach ($labels as $k => $v) {
if ($diff->$k) {
$return[] = $diff->$k . ' ' . $v . ($diff->$k > 1 ? 's' : '');
}
}
return implode(', ', $return);
}
This function can be shorter/better; but that is your job now ;)
It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
I need to compare a date to today. Basically I put in 2/17/13 and it will output "yesterday". I've tried echo date('l jS F', strtotime('2/15/13')); but it will only display that date not compare it to today.
From http://www.highlystructured.com/comparing_dates_php.html
$exp_date = "2006-01-16";
$todays_date = date("Y-m-d");
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
$valid = "yes";
} else {
$valid = "no";
}
Here's an example, to get you started:
$when = '2/17/13';
$now = new DateTime();
// I append $now's time to $then, to make sure we compare
// the two dates using the same time of the day
// if you want to compare to $then at 00:00:00, leave it out
$then = new DateTime( $when . ' ' . $now->format( 'H:i:s' ) );
$diff = $now->diff( $then );
switch( $diff->days )
{
case 0:
echo 'today';
break;
case 1:
echo $diff->invert ? 'yesterday' : 'tomorrow';
break;
default:
echo $diff->invert ? $diff->days . ' days ago' : $diff->days . ' days from now';
break;
}
Drupal ships with a very nice format_interval($interval, $granularity = 2, $langcode = NULL) function.
<?php
function format_interval($interval, $granularity = 2, $langcode = NULL) {
$units = array(
'1 year|#count years' => 31536000,
'1 month|#count months' => 2592000,
'1 week|#count weeks' => 604800,
'1 day|#count days' => 86400,
'1 hour|#count hours' => 3600,
'1 min|#count min' => 60,
'1 sec|#count sec' => 1,
);
$output = '';
foreach ($units as $key => $value) {
$key = explode('|', $key);
if ($interval >= $value) {
$output .= ($output ? ' ' : '') . format_plural(floor($interval / $value), $key[0], $key[1], array(), array('langcode' => $langcode));
$interval %= $value;
$granularity--;
}
if ($granularity == 0) {
break;
}
}
return $output ? $output : t('0 sec', array(), array('langcode' => $langcode));
}
?>
You don't need to be running Drupal to use it. Just include the above function somewhere. However, the above function also calls format_plural() - which calls t() (both custom Drupal functions), so you'll need to modify the above function or include all of them.
Your use case:
<?php
$today = date();
$compare = strtotime('2/15/13');
$interval = ($today - $compare);
print format_interval($interval, 1);
// Outputs '1 day'
?>
function checkDate($todaysDate,$expirationDate){
$today = strtotime($todays_date);
$expiration_date = strtotime($exp_date);
if ($expiration_date > $today) {
$valid = "yes";
} else {
$valid = "no";
}
return $valid
}
$expirationDate = "2006-01-16";
$todaysDate = date("Y-m-d");
$valid=checkDate($todaysDate,$expirationDate)
Do it in a function then you can use it with any combination of dates. You can then expand upon the function with some conditionals to figure out if its "yesterday".
function relativeTime($time) {
$d[0] = array(1,"second");
$d[1] = array(60,"minute");
$d[2] = array(3600,"hour");
$d[3] = array(86400,"day");
$d[4] = array(604800,"week");
$d[5] = array(2592000,"month");
$d[6] = array(31104000,"year");
$w = array();
$return = "";
$now = time();
$diff = ($now-$time);
$secondsLeft = $diff;
for($i=6;$i>-1;$i--)
{
$w[$i] = intval($secondsLeft/$d[$i][0]);
$secondsLeft -= ($w[$i]*$d[$i][0]);
if($w[$i]!=0)
{
$return.= abs($w[$i]) . " " . $d[$i][1] . (($w[$i]>1)?'s':'') ." ";
}
}
$return .= ($diff>0)?"ago":"left";
return $return;
}
I've searched around for calendars that is on PHP but all I searched are date time picker.
But what I only want is a simple calendar that shows me the date, without picking them.
I just need the calendar to display simply like how a normal calendar works in our Operating System, thanks.
Is there any way?
Here's one you can use: http://keithdevens.com/software/php_calendar
<?php
//http://keithdevens.com/software/php_calendar
$time = time();
$today = date('j', $time);
$days = array($today => array(null, null,'<div id="today">' . $today . '</div>'));
$pn = array('«' => date('n', $time) - 1, '»' => date('n', $time) + 1);
echo generate_calendar(date('Y', $time), date('n', $time), $days, 1, null, 0);
// PHP Calendar (version 2 . 3), written by Keith Devens
// http://keithdevens . com/software/php_calendar
// see example at http://keithdevens . com/weblog
// License: http://keithdevens . com/software/license
function generate_calendar($year, $month, $days = array(), $day_name_length = 3, $month_href = NULL, $first_day = 0, $pn = array())
{
$first_of_month = gmmktime(0, 0, 0, $month, 1, $year);
// remember that mktime will automatically correct if invalid dates are entered
// for instance, mktime(0,0,0,12,32,1997) will be the date for Jan 1, 1998
// this provides a built in "rounding" feature to generate_calendar()
$day_names = array(); //generate all the day names according to the current locale
for ($n = 0, $t = (3 + $first_day) * 86400; $n < 7; $n++, $t+=86400) //January 4, 1970 was a Sunday
$day_names[$n] = ucfirst(gmstrftime('%A', $t)); //%A means full textual day name
list($month, $year, $month_name, $weekday) = explode(',', gmstrftime('%m, %Y, %B, %w', $first_of_month));
$weekday = ($weekday + 7 - $first_day) % 7; //adjust for $first_day
$title = htmlentities(ucfirst($month_name)) . $year; //note that some locales don't capitalize month and day names
//Begin calendar . Uses a real <caption> . See http://diveintomark . org/archives/2002/07/03
#list($p, $pl) = each($pn); #list($n, $nl) = each($pn); //previous and next links, if applicable
if($p) $p = '<span class="calendar-prev">' . ($pl ? '' . $p . '' : $p) . '</span> ';
if($n) $n = ' <span class="calendar-next">' . ($nl ? '' . $n . '' : $n) . '</span>';
$calendar = "<div class=\"mini_calendar\">\n<table>" . "\n" .
'<caption class="calendar-month">' . $p . ($month_href ? '' . $title . '' : $title) . $n . "</caption>\n<tr>";
if($day_name_length)
{ //if the day names should be shown ($day_name_length > 0)
//if day_name_length is >3, the full name of the day will be printed
foreach($day_names as $d)
$calendar .= '<th abbr="' . htmlentities($d) . '">' . htmlentities($day_name_length < 4 ? substr($d,0,$day_name_length) : $d) . '</th>';
$calendar .= "</tr>\n<tr>";
}
if($weekday > 0)
{
for ($i = 0; $i < $weekday; $i++)
{
$calendar .= '<td> </td>'; //initial 'empty' days
}
}
for($day = 1, $days_in_month = gmdate('t',$first_of_month); $day <= $days_in_month; $day++, $weekday++)
{
if($weekday == 7)
{
$weekday = 0; //start a new week
$calendar .= "</tr>\n<tr>";
}
if(isset($days[$day]) and is_array($days[$day]))
{
#list($link, $classes, $content) = $days[$day];
if(is_null($content)) $content = $day;
$calendar .= '<td' . ($classes ? ' class="' . htmlspecialchars($classes) . '">' : '>') .
($link ? '' . $content . '' : $content) . '</td>';
}
else $calendar .= "<td>$day</td>";
}
if($weekday != 7) $calendar .= '<td id="emptydays" colspan="' . (7-$weekday) . '"> </td>'; //remaining "empty" days
return $calendar . "</tr>\n</table>\n</div>\n";
}
?>
It's a pretty basic mini calendar. No fancy functions.
I have written just one such with PHP5 + ajax(if you are need to use it):
<?php
class PN_Calendar {
public $first_day_of_week = 0; //0 - sunday, 1 - monday
public $current_year = null;
public $current_month = null;
public $current_day = null;
public $show_year_selector = true;
public $min_select_year = 1991;
public $max_select_year = 2045;
public $show_month_selector = true;
public function __construct($atts = array()) {
if (isset($atts['first_day_of_week'])) {
$this->first_day_of_week = $atts['first_day_of_week'];
}
if (!isset($atts['year'])) {
$this->current_year = date('Y');
} else {
$this->current_year = $atts['year'];
}
if (!isset($atts['month'])) {
$this->current_month = date('m');
} else {
$this->current_month = $atts['month'];
}
if (!isset($atts['day'])) {
$this->current_day = date('d');
} else {
$this->current_day = $atts['day'];
}
//***
if (isset($atts['show_year_selector'])) {
$this->show_year_selector = $atts['show_year_selector'];
}
if (isset($atts['show_month_selector'])) {
$this->show_month_selector = $atts['show_month_selector'];
}
if (isset($atts['min_select_year'])) {
$this->min_select_year = $atts['min_select_year'];
}
if (isset($atts['max_select_year'])) {
$this->max_select_year = $atts['max_select_year'];
}
}
/*
* Month calendar drawing
*/
public function draw($data = array(), $y = 0, $m = 0) {
//***
if ($m == 0 AND $m == 0) {
$y = $this->current_year;
$m = $this->current_month;
}
//***
$data['week_days_names'] = $this->get_week_days_names(true);
$data['cells'] = $this->generate_calendar_cells($y, $m);
$data['month_name'] = $this->get_month_name($m);
$data['year'] = $y;
$data['month'] = $m;
return $this->draw_html('calendar', $data);
}
private function generate_calendar_cells($y, $m) {
$y = intval($y);
$m = intval($m);
//***
$first_week_day_in_month = date('w', mktime(0, 0, 0, $m, 1, $y)); //from 0 (sunday) to 6 (saturday)
$days_count = $this->get_days_count_in_month($y, $m);
$cells = array();
//***
if ($this->first_day_of_week == $first_week_day_in_month) {
for ($d = 1; $d <= $days_count; $d++) {
$cells[] = new PN_CalendarCell($y, $m, $d);
}
//***
$cal_cells_left = 5 * 7 - $days_count;
$next_month_data = $this->get_next_month($y, $m);
for ($d = 1; $d <= $cal_cells_left; $d++) {
$cells[] = new PN_CalendarCell($next_month_data['y'], $next_month_data['m'], $d, false);
}
} else {
//***
if ($this->first_day_of_week == 0) {
$cal_cells_prev = 6 - (7 - $first_week_day_in_month); //checked, is right
} else {
if ($first_week_day_in_month == 1) {
$cal_cells_prev = 0;
} else {
if ($first_week_day_in_month == 0) {
$cal_cells_prev = 6 - 1;
} else {
$cal_cells_prev = 6 - (7 - $first_week_day_in_month) - 1;
}
}
}
//***
$prev_month_data = $this->get_prev_month($y, $m);
$prev_month_days_count = $this->get_days_count_in_month($prev_month_data['y'], $prev_month_data['m']);
for ($d = $prev_month_days_count - $cal_cells_prev; $d <= $prev_month_days_count; $d++) {
$cells[] = new PN_CalendarCell($prev_month_data['y'], $prev_month_data['m'], $d, false);
}
//***
for ($d = 1; $d <= $days_count; $d++) {
$cells[] = new PN_CalendarCell($y, $m, $d);
}
//***
//35(7*5) or 42(7*6) cells
$busy_cells = $cal_cells_prev + $days_count;
$cal_cells_left = 0;
if ($busy_cells < 35) {
$cal_cells_left = 35 - $busy_cells - 1;
} else {
$cal_cells_left = 42 - $busy_cells - 1;
}
//***
if ($cal_cells_left > 0) {
$next_month_data = $this->get_next_month($y, $m);
for ($d = 1; $d <= $cal_cells_left; $d++) {
$cells[] = new PN_CalendarCell($next_month_data['y'], $next_month_data['m'], $d, false);
}
}
}
//***
return $cells;
}
public function get_next_month($y, $m) {
$y = intval($y);
$m = intval($m);
//***
$m++;
if ($m % 13 == 0 OR $m > 12) {
$y++;
$m = 1;
}
return array('y' => $y, 'm' => $m);
}
public function get_prev_month($y, $m) {
$y = intval($y);
$m = intval($m);
//***
$m--;
if ($m <= 0) {
$y--;
$m = 12;
}
return array('y' => $y, 'm' => $m);
}
public function get_days_count_in_month($year, $month) {
return $month == 2 ? ($year % 4 ? 28 : ($year % 100 ? 29 : ($year % 400 ? 28 : 29))) : (($month - 1) % 7 % 2 ? 30 : 31);
}
public static function get_month_name($m) {
$names = self::get_monthes_names();
return $names[intval($m)];
}
public function get_week_day_name($num, $shortly = false) {
$names = $this->get_week_days_names($shortly);
return $names[intval($num)];
}
public function get_week_days_names($shortly = false) {
if ($this->first_day_of_week == 1) {
if ($shortly) {
return array(
1 => 'Mo',
2 => 'Tu',
3 => 'We',
4 => 'Th',
5 => 'Fr',
6 => 'Sa',
7 => 'Su'
);
}
return array(
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday',
7 => 'Sunday'
);
} else {
if ($shortly) {
return array(
0 => 'Su',
1 => 'Mo',
2 => 'Tu',
3 => 'We',
4 => 'Th',
5 => 'Fr',
6 => 'Sa'
);
}
return array(
0 => 'Sunday',
1 => 'Monday',
2 => 'Tuesday',
3 => 'Wednesday',
4 => 'Thursday',
5 => 'Friday',
6 => 'Saturday'
);
}
}
public static function get_monthes_names() {
return array(
1 => 'January',
2 => 'February',
3 => 'March',
4 => 'April',
5 => 'May',
6 => 'June',
7 => 'July',
8 => 'August',
9 => 'September',
10 => 'October',
11 => 'November',
12 => 'December'
);
}
public function draw_html($view, $data = array()) {
#extract($data);
ob_start();
include('views/' . $view . '.php' );
return ob_get_clean();
}
}
class PN_CalendarCell {
public $cell_year = null;
public $cell_month = null;
public $cell_day = null;
public $in_current_month = true;
public function __construct($y, $m, $d, $in_current_month = true) {
$this->cell_year = $y;
$this->cell_month = $m;
$this->cell_day = $d;
$this->in_current_month = $in_current_month;
}
public function get_week_day_num() {
return date('w', mktime(0, 0, 0, $this->cell_month, $this->cell_day, $this->cell_year)); //from 0 (sunday) to 6 (saturday);
}
public function draw($events) {
$this_day_events = 0;
if (is_array($events)) {
if (isset($events[$this->cell_year][$this->cell_month][$this->cell_day])) {
$this_day_events = count($events[$this->cell_year][$this->cell_month][$this->cell_day]);
}
} else {
$events = array();
}
?>
<span class="pn_cal_cell_ev_counter" <?php if ($this_day_events <= 0): ?>style="display: none;"<?php endif; ?>><?php echo $this_day_events ?></span>
<a data-year="<?php echo $this->cell_year ?>" data-month="<?php echo $this->cell_month ?>" data-day="<?php echo $this->cell_day ?>" data-week-day-num="<?php echo $this->get_week_day_num() ?>" href="javascript:void(0);" class="<?php if ($this->in_current_month): ?>pn_this_month<?php else: ?>other_month<?php endif; ?>"><?php echo $this->cell_day ?></a>
}
}
Script calling:
<?php
include_once 'classes/calendar.php';
$calendar = new PN_Calendar();
echo $calendar->draw();
?>
Download script with demo: http://pluginus.net/archives/simple-free-open-source-ajax-php-calendar-script
Demo: http://demo.pluginus.net/calendar/
I also was looking for a simple solution, a PHP class that rendered me a monthly calendar where I could add easily events.
I've found this PHP Calendar http://coreyworrell.com/calendar/
You have to still create a view/template in html, but you can find a CSS and HTML version there that you can use.
And it has custom events also in PHP
$event = $calendar->event()
->condition('timestamp', strtotime('January 2, 2010'))
->title('Hello All')
->output('My Custom Event')
->add_class('custom-event-class');