Number of intersections between 2 date ranges - php

I have 2 date ranges in my Codeigniter App, and i want to calculate the number of days that intersects between those to ranges. any ideas?
Date1start = YYYY-MM-DD;
Date1end = YYYY-MM-DD;
Date2start = YYYY-MM-DD;
Date2end = YYYY-MM-DD;

Something like this should work
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo min($datetimeEnd1,$datetimeEnd2)->diff(max($datetimeStart2,$datetimeStart1))->days+1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/9Pecb
Only for PHP 5.2
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeStart1 = $datetimeStart1->format('U');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeEnd1 = $datetimeEnd1->format('U');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeStart2 = $datetimeStart2->format('U');
$datetimeEnd2 = new DateTime('2015-12-28');
$datetimeEnd2 = $datetimeEnd2->format('U');
// following http://stackoverflow.com/questions/325933/determine-whether-two-date-ranges-overlap
if ($datetimeStart1 < $datetimeEnd2 && $datetimeEnd1 > $datetimeStart2) {
echo round(
((min($datetimeEnd1,$datetimeEnd2)) - (max($datetimeStart2,$datetimeStart1))) / (60*60*24)) + 1;
} else {
echo 'no overlap';
}
Demo: http://3v4l.org/a1WLk

Write it easy:
$datetimeStart1 = new DateTime('2015-12-10');
$datetimeEnd1 = new DateTime('2015-12-20');
$datetimeStart2 = new DateTime('2015-12-12');
$datetimeEnd2 = new DateTime('2015-12-28');
$start = max($datetimeStart2,$datetimeStart1);
$end = min($datetimeEnd1,$datetimeEnd2);
echo $end >= $start ? $end->diff($start)->days+1 : "no overlap";

Related

How to retrieve all media entries in Kaltura, beyond the 10k mark?

I am using the php5.3 SDK: https://github.com/kaltura/KalturaGeneratedAPIClientsPHP53
We have 90k media entries, but I can only got 20k entries. The following code is straight forward. Could anyone help me out?
// Main entry point
public function mywrite(Route $route, Console $console)
{
// Max records is 500, the range cannot be too big.
$range = 3600 * 24;
$this->__mywrite($route, $console, $range);
}
// Count how many objects we can get
// $veryStartDate == 1446173087, sep 2015
// $maxDate == 1526469375, may 2018
public function __mywrite($route, $console, $range) {
$configObj = $this->readMyWriteHistoryConfigFile();
$lastProcessObj = $this->readMyWriteLastProcessFile();
//
$veryStartDate = $configObj->veryStartDate;
$maxDate = $configObj->maxDate;
// Set start Date
$startDate = $veryStartDate;
$endDate = $startDate + $range;
//
$totalCount = 0;
while($startDate <= $maxDate) {
$objs = $this->listMediaByLastPlay($startDate, $endDate);
$totalCount += count($objs);
echo "\n$startDate - $endDate:\n";
echo "\n". count($objs). "\n";
$startDate = $endDate + 1;
$endDate = $endDate + $range;
} // end while loop
// we get like 25k records, but we have 90k records....
echo "\ncount: $totalCount\n";
}
// we call the client and get records by start last play date and end last play date
public function listMediaByLastPlay($startDate, $endDate) {
// Page size
$pageSize = 1000;
// Client with admin
$client = $this->getClient(\KalturaSessionType::ADMIN);
// media
$mediaObj = $client->media;
// Set a range to pull, order by last played at
$filter = new \KalturaMediaEntryFilter();
$filter->lastPlayedAtGreaterThanOrEqual = $startDate;
$filter->lastPlayedAtLessThanOrEqual = $endDate;
$filter->orderBy = '+lastPlayedAt';
// We still want more records
$pager = new \KalturaFilterPager();
$pager->pageSize = $pageSize;
// now list.....
$arr = $mediaObj->listAction($filter, $pager)->objects;
$buf = array();
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
return $buf;
}
You're iterating on the first page of each response, there might be more that one page.
The kaltura ListResponse has a totalCount property.
so you code should something like:
$pager = new \KalturaFilterPager();
$pageIndex = 1;
$entriesGot = 0;
$buf = array();
do
{
$pager->pageSize = $pageSize;
$pager->pageIndex = $pageIndex++;
// now list.....
$response = $mediaObj->listAction($filter, $pager);
$arr = $response->objects;
$entriesGot += count($arr);
foreach($arr as $k => $v) {
$t = array();
$t['dataUrl'] = $v->dataUrl;
$t['flavorParamsIds'] = $v->flavorParamsIds;
$t['plays'] = $v->plays;
$t['views'] = $v->views;
$t['lastPlayedAt'] = $v->lastPlayedAt;
$buf[] = $t;
}
}while($entriesGot < $response->totalCount);

How to add two times in PHP

I need to add two times and want to get total hours.
Here is my code:
foreach($result_data as $res) {
if( !empty($res['in1']) && !empty($res['out1']) ) {
$in1 = new DateTime($res['in1']);
$out1 = new DateTime($res['out1']);
$interval1 = $in1->diff($out1);
$h1 = $interval1->format('%H') . ":" . $interval1->format('%I');
$h2 = $h3 = "00:00";
if( !empty($res['in2']) && !empty($res['out2']) ) {
$in2 = new DateTime($res['in2']);
$out2 = new DateTime($res['out2']);
$interval2 = $in2->diff($out2);
$h2 = $interval2->format('%H') . ":" . $interval2->format('%I');
if( !empty($res['in3']) && !empty($res['out3']) ) {
$in3 = new DateTime($res['in3']);
$out3 = new DateTime($res['out3']);
$interval3 = $in2->diff($out3);
$h3 = $interval3->format('%H') . ":" . $interval3->format('%I');
}
}
$hours = strtotime($h1) + strtotime($h2) + strtotime($h3);
$res['total_hours'] = date("H:I", $hours);
$res_data[] = $res;
}
}
The error am getting is
date() expects parameter 2 to be integer, float given in
Can anyone please help me to find out the issue? Why $hours is float value?

How to show event date highlight(from database) in calender php

I am using php in my project, for which I am using a JavaScript calendar. I have an event date in my database, which I want to highlight in my calendar. I have tried the following code:
PHP
$items = '';
$selq = mysql_query("SELECT * FROM ".$gettn." WHERE template_content_id = '$gettid'");
$fetselq = mysql_fetch_array($selq);
$linkId1 = $fetselq['id'];
$getevent1 = mysql_query("SELECT * FROM `template3event` WHERE tl3_id = '$linkId1'");
//$items = array();
while($fetcgetevent1 = mysql_fetch_array($getevent1)){
$items .= date('d-F', strtotime($fetcgetevent1['date'])).',';
}
$event_date = substr($items, 0, -1);
$event_dates = explode(',', $event_date);
$Event_count = substr_count($event_date , ',');
// for($z = 0; $z <= $Event_count; $z++){
// echo $event_dates[$z].'<br>';
// }
JavaScript
// fill the month table with column headings
function day_title(day_name){
document.write("<TD ALIGN=center WIDTH=35>"+day_name+"</TD>")
}
// fills the month table with numbers
function fill_table(month,month_length)
{
day=1
// begin the new month table
document.write("<DIV CLASS='calender slide1'><P>"+month+" "+year+"</P>")
document.write("<TABLE width='240'><TR>")
// column headings
day_title("S")
day_title("M")
day_title("T")
day_title("W")
day_title("T")
day_title("F")
day_title("S")
// pad cells before first day of month
document.write("</TR><TR>")
for (var i=1;i<start_day;i++){
document.write("<TD>")
}
// fill the first week of days
for (var i=start_day;i<8;i++){
document.write("<TD><a href='#'>"+day+"</a></TD>")
day++
}
document.write("<TR>")
// fill the remaining weeks
while (day <= month_length) {
for (var i=1;i<=7 && day<=month_length;i++){
var getcurrentmonth= $('#hiddenmonth').val();
var getcurrentdate=$('#hiddendate').val();
if(getcurrentmonth === month)
{
if(getcurrentdate == day )
{
document.write("<TD><a style='color:rgb(65, 255, 0)' href='#'>"+day+"</a></TD>")
}
else
{
document.write("<TD><a href='#'>"+day+"</a></TD>")
}
}
else
{
document.write("<TD><a href='#'>"+day+"<a></TD>")
}
day++
}
document.write("</TR><TR>")
// the first day of the next month
start_day=i
}
document.write("</TR></TABLE></DIV>")
}
// end hiding -->
// CAHNGE the below variable to the CURRENT YEAR
var d = new Date();
var n = d.getFullYear();
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var mm = month[d.getMonth()];
var dd=d.getDate();
today = mm+'/'+dd+'/'+n;
year=n
var leap = ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
var add = 0;
if(leap == true ){
add = 1;
}
//alert(add);
$('#hiddenmonth').val(mm);
$('#hiddendate').val(dd);
// first day of the week of the new year
today= new Date("January 1, "+year)
start_day = today.getDay() + 1 // starts with 0
fill_table("January",31)
fill_table("February",28+add)
fill_table("March",31)
fill_table("April",30)
fill_table("May",31)
fill_table("June",30)
fill_table("July",31)
fill_table("August",31)
fill_table("September",30)
fill_table("October",31)
fill_table("November",30)
fill_table("December",31)
I have used a query to fetch data from the database. I don't know how to proceed to the next step. I only want to use this script to achieve this, I don't want to use jQuery.

How do i get grouped random numbers in different time intervals using php

I have failed to find any problem with my code, yet it only outputs numbers from 0 to 20 without following the time restrictions i imposed. Please help me out. Below is the code:
<!DOCTYPE html>
<html>
<?php
set_time_limit(0);
class random{
var $max;
var $min;
function irregularnos($min,$max) {
$num = '';
$i = 0;
$this->min=$min;
$this->max=$max;
while($i < 25)
{
$num .= mt_rand($min,$max);
echo $num . "</br>";
$num = '';
$i++;
}
}
}
$rand1 = new random;
$rand2 = new random;
$rand3 = new random;
$rand4 = new random;
date_default_timezone_set('Europe/Berlin');
$start_time = new DateTime(); //current time
while(true){
if ($start_time->modify('+1 seconds')<= new DateTime() and $start_time->modify('+2 seconds') > new DateTime()) { $rand2->irregularnos(21,50);}
else if ($start_time->modify('+2 seconds') <= new DateTime() and $start_time- >modify('+3 seconds') > new DateTime()) { $rand3->irregularnos(51,70);}
else if ($start_time->modify('+3 seconds') <= new DateTime() and $start_time->modify('+4 seconds') > new DateTime()) {$rand4->irregularnos(71,100);}
else if (new DateTime() < $start_time->modify('+1 seconds')) {$rand1->irregularnos(0,20);}
else if(new DateTime()> $start_time->modify('+4 seconds')) { break;}
}
?>
The code is working. Probably you are expecting the code to run only once per each random number, while in reality the loop may execute very many times, say, 50 times in the first second.
For that whole second, the condition that ensues is that time is between start_time and start_time + 1 second, so the 0-20 sequence is activated.
Also, note that you are not using properly your objects - for example, the instance variables min and max are never actually used, and your call prototype would make it pointless to declare four number generators.
This code has an added pause to show all the numbers being generated:
<?php
set_time_limit(0);
class random{
var $min;
var $max;
function __construct($min, $max) {
$this->min = $min;
$this->max = $max;
}
function irregularnos($n) {
for ($i = 0; $i < $n; $i++) {
$num = mt_rand($this->min, $this->max);
echo $num . '</br>';
}
}
}
$rand1 = new random(0,20);
$rand2 = new random(21,50);
$rand3 = new random(51,70);
$rand4 = new random(71,100);
date_default_timezone_set('Europe/Berlin');
$start_time = time();
for($quit = false; !$quit;) {
// How much time has elapsed since $start_time?
switch(time() - $start_time)
{
case 0: $rand1->irregularnos(25); break;
case 1: $rand2->irregularnos(25); break;
case 2: $rand3->irregularnos(25); break;
case 3: $rand4->irregularnos(25); break;
default: $quit = true; break;
}
print "---\n";
usleep(500000);
}
?>

calculate total minutes of it's own ID in db table

I am trying to show some stats given date ranges. In table rows there are many ID's and trying to calculate total minutes of it's own ID.
Currently returns values as below:
{"id":"25","minute":13}
{"id":"17","minute":12}
{"id":"16","minute":10}
{"id":"17","minute":10}
{"id":"16","minute":4}
{"id":"34","minute":5}
{"id":"17","minute":21}
{"id":"30","minute":12}
{"id":"30","minute":13}
{"id":"30","minute":50}
Controller
public function actionStats() {
if (isset($_POST['begin'], $_POST['end'])) {
$begin = strtotime($_POST['begin']);
$end = strtotime($_POST['end']);
$Criteria = new CDbCriteria();
$Criteria->condition = "created >= $begin and created <= $end and status=1";
$transcripts = Transcripts::model()->findAll($Criteria);
foreach($transcripts as $transcript) {
$op = $transcript->opID;
$minute = $transcript->ended - $transcript->created;
echo json_encode(array("id" => $op, "minute" => floor($minute/60)));
}
}
}
I'd modify your code to look like:
public function actionStats()
{
if (isset($_POST['begin'], $_POST['end']))
{
$begin = strtotime($_POST['begin']);
$end = strtotime($_POST['end']);
$Criteria = new CDbCriteria();
$Criteria->condition = "created >= $begin and created <= $end and status=1";
$transcripts = Transcripts::model()->findAll($Criteria);
$transcriptTotals = array();
foreach($transcripts as $transcript)
{
$op = $transcript->opID;
$minute = $transcript->ended - $transcript->created;
if (array_key_exists($op, $transcriptTotals)) {
$transcriptTotals[$op] += floor($minute/60);
} else {
$transcriptTotals[$op] = floor($minute/60);
}
}
echo json_encode($transcriptTotals);
}
}
This should result in output that looks like:
{'1':'2', 'id':'sumOfMinutes', etc}
If your JSON needs to be like you specified above, you would have code like:
foreach ($transcriptTotals as $id=>$sum) {
echo json_encode(array('id'=>$id, 'minutes'=>$sum));
}
How about adding it up in the MySQL query already? E.g. with the SUM function:
http://dev.mysql.com/doc/refman/5.0/en/group-by-functions.html

Categories