current time lies between time range - php

i need to check whether the current time lies between the range
these r restaurant open timings ,timings can be like open now till next morning or closed for sometime same day and open next half same day till next day or midnight
examples
Case1: 10:00 01:00
Case2: 10:00 23:59
Case3: 10:00 00:00
Case4: 23:59 05:00
Case5: 08:35 15:30 && 17:30 02:00
Case6: 10:00 15:00 && 17:00 00:00
all the cases must be checked
if((strtotime($s)<=strtotime($myTime)) && (strtotime($e)>=strtotime($myTime)))
{$open =1;}
if($e=="00:00")
{ if((strtotime($s)<=strtotime($myTime))&& (strtotime($myTime)>=strtotime("00:00")))
{$open =1;}}
this is not working where m i going wrong

Something like this might work. I've not really tested it.
$currentTime = time();
function in_range($what, $min, $max) {
return $what >= $min && $what <= $max;
}
var_dump(in_range($currentTime, strtotime('08:35'), strtotime('15:30'));
// etc.

Use DateTime objects for comparison like this. See http://php.net/manual/en/class.datetime.php
$cases = array(
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("12:00:00"),
),
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("23:59:00"),
),
array(
'start' => new DateTime("10:00:00"),
'end' => new DateTime("00:00:00"),
),
array(
'start' => new DateTime("23:59:00"),
'end' => new DateTime("05:00:00"),
),
);
//adjust dates
$cases[2]['end']->modify('+1 day');
$cases[3]['start']->modify('-1 day');
$now = new DateTime();
foreach ($cases as $key => $value) {
if ($now > $value['start'] && $now < $value['end']) {
echo 'case ' . $key . ' ok' . PHP_EOL;
}
else {
echo 'case ' . $key . ' out of range' . PHP_EOL;
}
}

Right-o, had a mess around for you. Do you want to see if this is getting your expected output? Seems to be working on my local tests. Fair bit of code mind, turned out to be a few edge cases to consider.
Potentially bits of it that can be refactored and improved, but i'll leave that up to you if it works as intended.
<?php
$cases = [
[['start' => '09:00', 'end' => '01:00']],
[['start' => '10:00', 'end' => '23:59']],
[['start' => '10:00', 'end' => '00:00']],
[['start' => '23:59', 'end' => '05:00']],
[['start' => '10:00', 'end' => '15:00'], ['start' => '17:30', 'end' => '02:00']],
[['start' => '10:00', 'end' => '15:00'], ['start' => '17:30', 'end' => '00:00']],
];
$cases = setUpCases($cases);
foreach ($cases as $case) {
$withinTimeRange = isTimeWithinCase((new DateTime()), $case);
if ($withinTimeRange) {
break;
}
}
// Boolean True/False whether it is within any of the ranges or not.
// i.e. True = Shop Open, False = Shop closed.
var_dump($withinTimeRange);
function setUpCases($cases) {
return array_map(function($case) {
return convertToDateTimeObjects($case);
}, $cases);
}
function convertToDateTimeObjects($case) {
$formatted = [];
foreach ($case as $index => $times) {
$s = new DateTime();
list($hour, $minute) = explode(':', $times['start']);
$s->setTime($hour, $minute, 00);
$e = new DateTime();
list($hour, $minute) = explode(':', $times['end']);
$e->setTime($hour, $minute, 00);
if ($e < $s) $e->modify('+1 day');
$formatted[] = ['start' => $s, 'end' => $e];
}
return $formatted;
}
function isTimeWithinCase($time, $case) {
foreach ($case as $timerange) {
return ($time > $timerange['start'] && $time < $timerange['end']);
}
}

I have been thinking about this task carefully. And i came up with the logic that is required to calculate whether the current time is in between 2 times. There are the following two cases to calculate that:
Case 1: The starting time is greater than the ending time
Which means the ending time must be the next day. That means that if your current time is less than the ending time OR greater than the start time, your time is in between the two times.
Case 2: The starting time is less than the ending time
In this case, the start time and the ending time is the same day. For this, the logic that is needed is to check whether or not your time is greater than the start time AND less than the ending time. If that's statement is true, your time is in between the two times.
I have made the following function for calculating that:
function checktime($arr,$time) {
list($h,$m)=explode(":",$time);
if(!is_array($arr[0])) {
$r1=explode(":",$arr[0]);
$r2=explode(":",$arr[1]);
if($r1[0]>$r2[0]) {
if(($h>$r1[0] || ($h==$r1[0] && $m>=$r1[1])) || ($h<$r2[0] || ($h==$r2[0] && $m<=$r2[1]))) return true;
}
else {
if(($h>$r1[0] || ($h==$r1[0] && $m>=$r1[1])) && ($h<$r2[0] || ($h==$r2[0] && $m<=$r2[1]))) return true;
}
}
}
And here are some tests, for testing the limits of the cases you gave me:
$arr=array("10:00","01:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("10:00","23:59");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("10:00","00:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("23:59","05:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("08:35","15:30");
echo (checktime($arr,"23:59")?"True":"False");//False
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("17:30","02:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True
$arr=array("10:00","15:00");
echo (checktime($arr,"23:59")?"True":"False");//False
echo (checktime($arr,"12:00")?"True":"False");//True
echo (checktime($arr,"00:00")?"True":"False");//False
$arr=array("17:00","00:00");
echo (checktime($arr,"23:59")?"True":"False");//True
echo (checktime($arr,"12:00")?"True":"False");//False
echo (checktime($arr,"00:00")?"True":"False");//True

this works for all the casese
$let=array("01:00","02:00","03:00","05:00","04:00");
if((strtotime($s)<=strtotime($myTime)) && (!strcmp($e,"00:00")))
{ $open=1;$flag=1;}
if((strtotime($s)<=strtotime($myTime)) && (!strcmp($e,"23:59")))
{ $open=1;$flag=1;}
if(in_array($e,$let))
{
if(strtotime($s)<=strtotime($myTime))
{ $open=1;$flag=1;}
else
if(strtotime($e)>=strtotime($myTime))
{ $open=1;$flag=1;}
}
if(!$flag)
{if((strtotime($s)<=strtotime($myTime)) && (strtotime($e)>=strtotime($myTime)))
{ $open=1;} }

Related

How to call json from multiple nested if condition

I am using CodeIgniter. I am working on the small project which is a Batch list. Now If an admin wants to create the batch list then should enter the start date and end date and start time and end time then it will check in the database that batch is running on the same date and time? If yes then it will display the message if not then it will create a new batch list.
If the date is the same the time should be different.
Now My logic is,
I am comparing the first new_start_date with exist_start_date and exist_end_date if date found in between then it will check the time.
It's working till date compare. Even it's checking the time but from there how to exit the process and call the JSON? because from there my JSON not working.
I added "echo "time not match";" from there I am not able to call the JSON I am getting the output on my network tab.
I am getitng the output
enter 1enter 2{"error":true,"msg":"Batch Created"}time not match
Would you help me out in this?
$id = $this->input->post('venue_id');
$venue_id = implode(',',$id);
$activity_list_id = $this->input->post('activity_name');
$new_batch_start_date = date('Y-m-d',strtotime($this->input->post('start_date')));
$new_batch_end_date = date('Y-m-d',strtotime($this->input->post('end_date')));
$new_batch_start_time = $this->input->post('start_time');
$new_batch_end_time = $this->input->post('end_time');
$days = implode(',',$this->input->post('days'));
//print_r($days);
if($new_batch_start_date >= $new_batch_end_date)
{
$response['error'] = false;
$response['msg'] = "End Date Should be Greater than Start Date";
echo json_encode($response);
return false;
}
//convert in Time Format
$new_batch_start_time = strtotime($new_batch_start_time);
$new_batch_end_time = strtotime($new_batch_end_time);
$venue = $this->input->post('name');
$data = array(
'activity_list_id' => $this->input->post('activity_name'),
'batch_venue_id' => $venue_id,
'batch_name' => $this->input->post('batch_name'),
'start_date' => date('Y-m-d',strtotime($this->input->post('start_date'))),
'end_date' => date('Y-m-d',strtotime($this->input->post('end_date'))),
'start_time' => $this->input->post('start_time'),
'end_time' => $this->input->post('end_time'),
'total_capacity' => $this->input->post('total_capecity'),
'batch_status' => 1,
'created_by' => trim($this->session->userdata['login_data']['user_id']),
'created_date' => date('d-m-Y h:i:s A'),
'batch_days' => $days
);
$get_batch_details = $this->Batch_model->fetchBatches();
if(!empty($get_batch_details))
{
foreach ($get_batch_details as $rows)
{
$exist_batch_start_date = $rows->start_date;
$exist_batch_end_date = $rows->end_date;
$batch_time1 = strtotime($rows->start_time);
$batch_time2 = strtotime($rows->end_time);
$batch_venue_id = explode(',',$rows->batch_venue_id);
$common_venue_id = array_intersect($id,$batch_venue_id);
//print_r($common_venue_id);
if($common_venue_id)
{
echo "enter 1";
//if new batch start date between existing batch start date
if($exist_batch_start_date <= $new_batch_start_date && $exist_batch_end_date >= $new_batch_start_date ){
echo "enter 2";
if($batch_time1 <= $new_batch_start_time && $batch_time2 > $new_batch_start_time){
$msg = "Other Batch Alredy Running On from Date $batch_start_date to $exist_batch_end_date on Time : $batch_time1 to $batch_time2.
Please Change Time Slot or Start And End Date";
$response['error'] = false;
$response['msg'] = $msg;
echo json_encode($response);
exit;
}
else{
$result = $this->Batch_model->createBatch($data);
echo "time not match";
print_r($result);
}
break;
}
//if date is different
else
{
$result = $this->Batch_model->createBatch($data);
}
}else
{
$result = $this->Batch_model->createBatch($data);
}
}
}
//first time creating batch
else
{
$result = $this->Batch_model->createBatch($data);
}
Mobel
function createBatch($data){
if($this->db->insert('batch_list',$data))
{
$response['error'] = true;
$response['msg'] = "Batch Created";
echo json_encode($response);
}
else
{
$response['error'] = true;
$response['msg'] = "Failed to Create Batch";
echo json_encode($response);
}
}
function fetchBatches()
{
$result = $this->db->where(['batch_list.batch_status'=>1,'activity_list.act_status'=>1])
->from('batch_list')
->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
->get()
->result();
return $result;
}
Ajax
success: function(response){
var data = JSON.parse(response);
if (data.error == true){
swal({
title: "Success",
text: data.msg ,
type: "success"
}).then(function(){
location.reload();
}
);
} else {
swal({
title: "Warning",
text: data.msg ,
type: "warning"
});
}
}
Would you help me out in this issue?
your entire approach is a bit messy because you find yourself in a ton of redundant code fragments and nobody is able to understand what exactly you want - i gv you some hints here including an example based on your code
Use Exceptions - it's perfect for your case - if something goes wrong - stop it
Try to filter your need to an extent of one single task und try to solve it - and only after that go to the next task
Always - remember always - think about one term - if you find repeatedly the same code in your application - you know something is wrong - and you should refactor it - don't be ashamed about redundancies - they do always happen - but if you find them, you must refactor those code snippets
Now to your example
What are your tasks here ?
you can try to ask your database if a batch is already running - you dont need to iterate over the entire table entries
Compare both input Dates from Administrator - if start date is in the future of end date, instantely stop the application
your intersection isn't really clear to me what you want to achieve here - but i'm really convinced you can ask the database here too (catchword: find_in_set)
Based on that information we can start to develop things now ;) (if i don't have everything just complete the list above and try to implement your task)
Controller:
try
{
$id = $this->input->post('venue_id');
$venue_id = implode(',',$id);
$activity_list_id = $this->input->post('activity_name');
$new_batch_start_date = date('Y-m-d',strtotime($this->input->post('start_date')));
$new_batch_end_date = date('Y-m-d',strtotime($this->input->post('end_date')));
$new_batch_start_time = $this->input->post('start_time');
$new_batch_end_time = $this->input->post('end_time');
$days = implode(',',$this->input->post('days'));
$objDateStart = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_start_date.' '.$new_batch_start_time);
$objDateEnd = DateTime::createFromFormat('Y-m-d h:i a', $new_batch_end_date.' '.$new_batch_end_time);
if ($objDateEnd < $objDateStart) throw new Exception('End Date Should be Greater than Start Date');
if ($this->Batch_model->hasBatchesBetweenDates($objDateStart, $objDateEnd)) throw new Exception('Other Batch already running On from '.$objDateStart->format('d-m-Y H:i').' to '.$objDateEnd->format('d-m-Y H:i').'. Please Change Time Slot for Start and End Date');
$data = array(
'activity_list_id' => $this->input->post('activity_name'),
'batch_venue_id' => $venue_id,
'batch_name' => $this->input->post('batch_name'),
'start_date' => $objDateStart->format('Y-m-d'),
'end_date' => $objDateEnd->format('Y-m-d'),
'start_time' => $objDateStart->format('H:i'),
'end_time' => $objDateEnd->format('H:i'),
'total_capacity' => $this->input->post('total_capecity'),
'batch_status' => 1,
'created_by' => trim($this->session->userdata['login_data']['user_id']),
'created_date' => date('d-m-Y h:i:s A'),
'batch_days' => $days
);
$this->Batch_model->createBatch($data);
}
catch(Exception $e)
{
$arrError = [
'error' => false,
'msg' => $e->getMessage()
];
echo json_encode($arrError);
}
Model:
public function hasBatchesBetweenDates(DateTime $objDateStart, DateTime $objDateEnd)
{
$query = $this->db
->from('batch_list')
->join('activity_list','activity_list.activity_id = batch_list.activity_list_id')
->where('CONCAT(start_date,\' \',start_time) >=', $objDateStart->format('Y-m-d H:i:s'))
->or_group_start()
->where('CONCAT(end_date, \' \', end_time) <=', $objDateEnd->format('Y-m-d H:i:s'))
->where('CONCAT(end_date, \' \', end_time) >=', $objDateStart->format('Y-m-d H:i:s'))
->group_end()
->get();
return ($query->num_rows() > 0);
}
i hope you understand the concepts here - if you've questions - don't hesitate to ask

Finding between zodiac by only date and month

I'm quite frustrated with the following code, which should show the Zodiac sign of a baby by using only date and month.
$babyDue= date('d-m',strtotime("23-04-2015"));
$ariesStart=date('d-m',strtotime("21-03-2016"));
$ariesEnd=date('d-m',strtotime("20-04-2016"));
$taurusStart=date('d-m',strtotime("21-04-2016"));
$taurusEnd=date('d-m',strtotime("20-05-2016"));
$zodiac="thisTextNeedToChange";
if(($babyDue>$ariesStart) && ($babyDue<$ariesEnd)) {
//Set $zodiac to aries
$zodiac="aries";
echo $zodiac;
} elseif (($babyDue>$taurusStart)&& ($babyDue<$taurusEnd)){
//Set $zodiac to Taurus
$zodiac="Taurus";
echo $zodiac;
}
I think my logic is correct, but it's not showing anything :(
$babyBirthDate = new DateTime('23 April');
$zodiacs = array(
'Aries' => array(
new DateTime('21 March'),
new DateTime('20 April'),
),
'Taurus' => array(
new DateTime('21 April'),
new DateTime('20 May'),
)
);
foreach ($zodiacs as $zodiac => $dateTimeRange) {
if ($babyBirthDate >= $dateTimeRange[0] && $babyBirthDate <= $dateTimeRange[1]) {
echo $zodiac;
break;
}
}

Randomised Greeting Function - PHP

So, I have created a script in PHP that sets a greeting dependent on date and time. The code checks for any seasonal events, and if there are none, it checks the time and assigns the appropriate greeting. My issue that I am having is:
I have set the value to check if the time is past 18:00, if it is past this time, it should set an evening greeting. My issue is that if I change the php if argument value to a time in the future, it still keeps the greeting as an evening greeting. What could be wrong?
Here is my code:
$morningGreetings = array(
1 => "Good morning",
2 => "Morning",
);
$standardGreetings = array(
1 => "Hello",
2 => "Howdy",
3 => "Hiya",
4 => "Greetings",
5 => "Great to see you",
6 => "Hi there",
7 => "Hi",
8 => "Good day",
);
$eveningGreetings = array(
1 => "Evening",
2 => "Good evening",
);
$seasonalGreetings = array(
1 => "Merry Christmas",
2 => "Happy New Year",
);
$eventGreetings = array(
1 => "Happy Birthday",
);
if (date("d m") != strtotime("25 12")) {
if (date("d m") != strtotime("0 0")) {
if (date("G i") <= strtotime("18 00")) {
if (date("G i") <= strtotime("09 00")) {
$sizeOfArray = sizeof($standardGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $standardGreetings[$greetingValue];
} else {
$sizeOfArray = sizeof($morningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $morningGreetings[$greetingValue];
}
} else {
$sizeOfArray = sizeof($eveningGreetings);
$greetingValue = rand(1, $sizeOfArray);
$greeting = $eveningGreetings[$greetingValue];
}
} else {
$greeting = $seasonalGreetings[2];
}
} else {
$greeting = $seasonalGreetings[1];
}
Maybe something like this:
EDIT
$seasonalGreetingA=array();
$seasonalGreetingA[]=array('dayBegin'=>30,'monthBegin'=>12,'dayEnd'=>31,'monthEnd'=>12,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>1,'monthBegin'=>1,'dayEnd'=>2,'monthEnd'=>1,'text'=>'Happy New Year');
$seasonalGreetingA[]=array('dayBegin'=>21,'monthBegin'=>6,'dayEnd'=>23,'monthEnd'=>9,'text'=>'Happy Spring');
$seasonalGreetingA[]=array('dayBegin'=>12,'monthBegin'=>11,'dayEnd'=>23,'monthEnd'=>11,'text'=>'Happy All');
$dateGreetingA=array();
$dateGreetingA[]=array('date'=>'2014-11-09','text'=>'Happy Birthday');
$timeGreetingA=array();
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Morning');
$timeGreetingA[]=array('timeBegin'=>8,'timeEnd'=>12,'text'=>'Good morning');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Evening');
$timeGreetingA[]=array('timeBegin'=>18,'timeEnd'=>23,'text'=>'Good evening');
$timeGreetingA[]=array('timeBegin'=>23,'timeEnd'=>24,'text'=>'Time out');
$timeGreetingA[]=array('timeBegin'=>13,'timeEnd'=>18,'text'=>'Good afternoon');
$standardGreetingA[]=array();
$standardGreetingA[]=array('text'=>'Hello');
$standardGreetingA[]=array('text'=>'Howdy');
$standardGreetingA[]=array('text'=>'Hi');
$txtGreeting='';
$date=date('Y-m-d');
if($txtGreeting=='')
if(count($dateGreetingA)>0)
foreach($dateGreetingA as $dgA)
{
if($dgA['date']==$date)
{
$txtGreeting=$dgA['text'];
break;
}
}
$d=(int)date('d');
$m=(int)date('m');
if($txtGreeting=='')
if(count($seasonalGreetingA)>0)
foreach($seasonalGreetingA as $sgA)
{
$d1=$sgA['dayBegin'];
$m1=$sgA['monthBegin'];
$d2=$sgA['dayEnd'];
$m2=$sgA['monthEnd'];
//echo $m1.' >= '.$m.' <= '.$m2.'<br />';
if($m>=$m1 and $m<=$m2)
if($d>=$d1 and $d<=$d2)
$txtGreeting=$sgA['text'];
}
$time=(int)date('H');
if($txtGreeting=='')
if(count($timeGreetingA)>0)
foreach($timeGreetingA as $tgA)
{
if($time>=$tgA['timeBegin'] and $time<= $tgA['timeEnd'])
{
$txtGreeting=$tgA['text'];
break;
}
}
if($txtGreeting=='')
if(count($standardGreetingA)>0)
{
$ind=rand(0,count($standardGreetingA)-1);
if(isset($standardGreetingA[$ind])) $txtGreeting=$standardGreetingA[$ind]['text'];
}
echo $txtGreeting;
exit;

PHP if based on current system date

Trying to setup a page that auto updates based on the users date/time.
Need to run a promotion for 2 weeks and each day it needs to change the displayed image.
Was reading through http://www.thetricky.net/php/Compare%20dates%20with%20PHP to get a better handle on php's time and date functions.Somewhat tricky to test, but I basically got stuck on:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date() = $dateA){
echo 'todays message';
}
else if(date() = $dateB){
echo 'tomorrows message';
}
?>
I know the above function is wrong as its setup, but I think it explains what I am aiming for.
Time is irrelevant, it needs to switch over at midnight so the date will change anyway.
You seem to need this:
<?php
$dateA = '2012-07-16';
$dateB = '2012-07-17';
if(date('Y-m-d') == $dateA){
echo 'todays message';
} else if(date('Y-m-d') == $dateB){
echo 'tomorrows message';
}
?>
you want
<?php
$today = date('Y-m-d')
if($today == $dateA) {
echo 'todays message';
} else if($today == $dateB) {
echo 'tomorrows message';
}
?>
I would go a step back and handle it via file names. Something like:
<img src=/path/to/your/images/img-YYYY-MM-DD.jpg alt="alternative text">
So your script would look something like this:
<img src=/path/to/your/images/img-<?php echo date('Y-m-d', time()); ?>.jpg alt="alternative text">
If you're going to do date calculations, I'd recommend using PHP's DateTime class:
$promotion_starts = "2012-07-16"; // When the promotion starts
// An array of images that you want to display, 0 = the first day, 1 = the second day
$images = array(
0 => 'img_1_start.png',
1 => 'the_second_image.jpg'
);
$tz = new DateTimeZone('America/New_York');
// The current date, without any time values
$now = new DateTime( "now", $tz);
$now->setTime( 0, 0, 0);
$start = new DateTime( $promotion_starts, $tz);
$interval = new DateInterval( 'P1D'); // 1 day interval
$period = new DatePeriod( $start, $interval, 14); // 2 weeks
foreach( $period as $i => $date) {
if( $date->diff( $now)->format("%d") == 0) {
echo "Today I should display a message for " . $date->format('Y-m-d') . " ($i)\n";
echo "I would have displayed: " . $images[$i] . "\n"; // echo <img> tag
break;
}
}
Given that the promotion starts on 07-16, this displays the following, since it is now the second day of the promotion:
Today I should display a message for 2012-07-17 (1)
I would have displayed: the_second_image.jpg

How to extend or modify Codeigniter calendar to handle multi-day events and multiple events per day

I'd hate to reinvent the wheel on this one if it's out there somewhere, but has anyone extended or modified the codigniter calendar to handle multi-day events and multiple events per day or is it there a module available somewhere?
Multiple events for one day is actually very easy. It just takes changing the calendar template and here is an example from some of my code.
public function print_calendar($year = 0, $month = 0)
{
$prefs = array (
'show_next_prev' => FALSE,
'next_prev_url' => site_url('events/print_calendar'),
'day_type' => 'long',
'template' => '
{heading_row_start}{/heading_row_start}
{heading_previous_cell}{/heading_previous_cell}
{heading_title_cell}<h1>{heading}</h1>{/heading_title_cell}
{heading_next_cell}{/heading_next_cell}
{heading_row_end}{/heading_row_end}
{table_open}<table border="0" cellpadding="0" cellspacing="0">{/table_open}
{week_row_start}<tr>{/week_row_start}
{week_day_cell}<th bgcolor="#999999">{week_day}</th>{/week_day_cell}
{week_row_end}</tr>{/week_row_end}
{cal_row_start}<tr>{/cal_row_start}
{cal_cell_start}<td background="'.s3_path('images/print_cal_cell.jpg').'">{/cal_cell_start}
{cal_cell_content}<span class="cal_day">{day}</span>{content}{/cal_cell_content}
{cal_cell_content_today}<span class="cal_day">{day}</span>{/cal_cell_content_today}
{cal_cell_no_content}<span class="cal_day">{day}</span>{/cal_cell_no_content}
{cal_cell_no_content_today}<span class="cal_day">{day}</span>{/cal_cell_no_content_today}
{cal_cell_blank} {/cal_cell_blank}
{cal_cell_end}</td>{/cal_cell_end}
{cal_row_end}</tr>{/cal_row_end}
{table_close}</table>{/table_close}
'
);
$this->load->library('calendar', $prefs);
$year = ($year == 0) ? date('Y') : $year;
$month = ($month == 0) ? date('n') : $month;
$start = strtotime('1-'.$month.'-'.$year);
$events = $this->events_model->get_by_date($start, strtotime('+1 month', $start));
$this->template->set_layout('');
if ($events)
{
foreach ($events as $key => $event)
{
$day = date('j', $event['showing_start_time']);
$vars[$day] = $this->template->build('events/calendar/cal_item', $event, TRUE);
}
}
$vars['content'] = $this->calendar->generate($year, $month, $vars);
$this->load->view('calendar/cal_layout', $vars);
}
Hopefully that code is clear and can give you a good starting point. What I normally do if they span multiple days just include the item on each day.
This can be easily modified in the file system/libraries/Calendar.php with the following addition of code. I know that editing any system file is considered taboo, but this helped me out in my application a ton. Take note of the foreach() loop in the commented section that says //If more than one event on the same day. This is the code that needs to be added to the Calendar.php library file. This resource can be futher elaborated on at the following link.
http://codeigniter.com/forums/viewthread/196998/
Calendar.php modified code:
if (isset($data[$day]))
{
// Cells with content
$temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_content_today'] : $this->temp['cal_cell_content'];
// If more than one event on the same day
if (is_array($data[$day]))
{
$several_events = '';
foreach ($data[$day] as $key => $value)
{
$several_events .= '<li id="'.$key.'">'.$value.'</li>';
}
$out .= str_replace('{day}', $day, str_replace('{content}', $several_events, $temp));
}
// One event per day
else
{
$out .= str_replace('{day}', $day, str_replace('{content}', $data[$day], $temp));
}
}
else
{
// Cells with no content
$temp = ($is_current_month == TRUE AND $day == $cur_day) ? $this->temp['cal_cell_no_content_today'] : $this->temp['cal_cell_no_content'];
$out .= str_replace('{day}', $day, $temp);
}
}
else
{
// Blank cells
$out .= $this->temp['cal_cell_blank'];
}
Keep in mind that I've shown more than just the edited code above to help you locate it within Calendar.php. I hope this helps!

Categories