PHP: Time slot, how much time on morning and on night? - php

Suppose I have two strings like "08:50" (start) and "23:50" (end).
Now I know that the morning is from 06:00 to 22:00 and the night is from 22:00 and 06:00.
The question is, how can I know how much time is in the morning and how much in the night? It should be 9 hours in the morning and 1 hour 50 minutes in the night.
I have done a code, but sometimes (with particolar values) it crashes, and it loses couple of minutes:
function analizza_mattina_sera($result2)
{
$inizio_giorno = oreToMinuti("06:00");
$fine_giorno = oreToMinuti("22:00");
$inizio_notte = oreToMinuti("22:00");
$fine_notte = oreToMinuti("06:00");
$conto_minuti_giorno = "";
$conto_minuti_notte = "";
while ($row2 = mysql_fetch_array($result2)) {
$data1 = strtotime($row2["anno"]
."-". $row2["mese"]
."-". $row2["giorno"]
." ". $row2["ora_effettiva"]);
$data2 = strtotime($row2["anno"]
."-". $row2["mese"]
."-". $row2["giorno"]
." ". $row2["ora_teorica"]);
$differenza = (($data2 - $data1) / 3600) / (1 / 60);
if ($row2["verso"] == "entrata") {
$ora_usa = $row2["ora_effettiva"];
if (oreToMinuti($ora_usa) < $inizio_giorno) {
$conto_minuti_notte = $fine_notte - oreToMinuti($ora_usa);
}
if (oreToMinuti($ora_usa) > $inizio_giorno) {
$conto_minuti_giorno = oreToMinuti($ora_usa) - $inizio_giorno;
}
}
else {
$ora_usa = $row2["ora_effettiva"];
if (oreToMinuti($ora_usa) < $fine_giorno) {
if (oreToMinuti($ora_usa) < $fine_notte) {
$conto_minuti_notte = ($fine_notte - oreToMinuti($ora_usa)) - $conto_minuti_notte;
}
else {
$conto_minuti_giorno = oreToMinuti($ora_usa) - $inizio_giorno - $conto_minuti_giorno;
}
}
else {
$conto_minuti_notte = oreToMinuti($ora_usa) - $inizio_notte;
$conto_minuti_giorno = $fine_giorno - $conto_minuti_giorno - $inizio_giorno;
}
}
}
return str_replace("-", "", ($conto_minuti_giorno == "" ? 0 : $conto_minuti_giorno)
."_". ($conto_minuti_notte == "" ? 0 : $conto_minuti_notte)) ."<br />";
}

You can try this (you should add some validation).
Here is how to use it, it will return an array of morning period in minutes and night period in minutes:
categorizePeriod('08:50', '23:50');
Here are the functions:
function minutesDiff($startTime, $endTime)
{
$isNextDay = ($startTime > $endTime) ? 1 : 0;
$start = explode(':', $startTime);
$end = explode(':', $endTime);
$diffInSeconds = abs(mktime($start[0], $start[1], 0, null, date('j'), null) - mktime($end[0], $end[1], 0, null, date('j') + $isNextDay, null));
return floor($diffInSeconds/60);
}
function inMorning($time, array $morning)
{
return ($morning[0] <= $time && $time <= $morning[1]);
}
function categorizePeriod($startTime, $endTime, array $morning = array('06:00', '22:00'))
{
if ($startTime == $endTime) {
return array(0, 0);
} else if ($startTime > $endTime) {
$beforeMidnight = categorizePeriod($startTime, '23:59', $morning);
$afterMidnight = categorizePeriod('00:00', $endTime, $morning);
return array(
$beforeMidnight[0] + $afterMidnight[0] + (int)inMorning('00:00', $morning),
$beforeMidnight[1] + $afterMidnight[1] + (int)!inMorning('00:00', $morning),
);
}
if (inMorning($startTime, $morning) && inMorning($endTime, $morning)) {
return array(
minutesDiff($startTime, $endTime),
0
);
} elseif (!inMorning($startTime, $morning) && !inMorning($endTime, $morning)) {
return array(
0,
minutesDiff($startTime, $endTime)
);
} elseif (inMorning($startTime, $morning) && !inMorning($endTime, $morning)) {
return array(
minutesDiff($startTime, $morning[1]),
minutesDiff($morning[1], $endTime)
);
} elseif (!inMorning($startTime, $morning) && inMorning($endTime, $morning)) {
return array(
minutesDiff($morning[0], $endTime),
minutesDiff($startTime, $morning[0])
);
}
}

I hope this is what you are looking for.. I have converted to hours..
Say for e.g.
Start - 4.30 and End - 21.30 then morning 15.5 hours and night 1.5 hours
Start - 4.30 and End - 22.30 then morning 16 hours and night 2 hours
Start - 6.30 and End - 21.30 then morning 15 hours and night 0 hours
Start - 6.30 and End - 22.30 then morning 15.5 hours and night 0.5 hours
Following is the script may be helpful to you.
<?php
//Get the timeslote how many hours spent in the morning and how many hours spent in the night
$start = "00:00";
$end = "00:00";
$morningSlote = "06:00 - 22:00";
$nightSlote = "22:00 - 06:00";
$startTime = strtotime($start);
$endTime = strtotime($end);
$startDate = date("m/d/Y");
$endDate = date("m/d/Y");
if($startTime > $endTime) {
//Date will be changed
//i.e. 11.30 PM - 2.30 AM
//i.e. 11.30 PM - 6.20 PM
$startDate = date("m/d/Y H:i:s",strtotime($start));
$endDate = date("m/d/Y H:i:s",strtotime("+1 day".$end));
} else if($endTime > $startTime) {
//No date will be changed
//i.e. 2.30 AM - 11.30 PM
//i.e. 2.30 AM - 6.30 AM
$startDate = date("m/d/Y H:i:s",strtotime($start));
$endDate = date("m/d/Y H:i:s",strtotime($end));
}
$output = getCorrectTimeslote($startDate, $endDate, $morningSlote, $nightSlote);
echo "<br>spent in the morning: ".$output["morningSession"]." Hours";
echo "<br>spent in the night: ".$output["nightSession"]." Hours";
function getCorrectTimeslote($startDate, $endDate, $morningSlote, $nightSlote) {
$output = array();
$morningSloteStart = "";
$morningSloteEnd = "";
$nightSloteStart = "";
$nightSloteEnd = "";
$morningSloteExplodedResult = array();
if(strpos($morningSlote,"-") !== false) {
$morningSloteExplodedResult = explode("-",$morningSlote);
$morningSloteStart = date("m/d/Y H:i:s",strtotime(trim($morningSloteExplodedResult[0])));
$morningSloteEnd = date("m/d/Y H:i:s",strtotime(trim($morningSloteExplodedResult[1])));
}
$nightSloteExplodedResult = array();
if(strpos($nightSlote,"-") !== false) {
$nightSloteExplodedResult = explode("-",$nightSlote);
$nightSloteStart = date("m/d/Y H:i:s",strtotime(trim($nightSloteExplodedResult[0])));
$nightSloteEnd = date("m/d/Y H:i:s",strtotime("+1 day".trim($nightSloteExplodedResult[1])));
}
if((isset($morningSloteStart) && !empty($morningSloteStart)) && (isset($morningSloteEnd) && !empty($morningSloteEnd)) && (isset($nightSloteStart) && !empty($nightSloteStart)) && (isset($nightSloteEnd) && !empty($nightSloteEnd))) {
$morningSession = 0;
$nightSession = 0;
if($endDate >= $startDate) {
if($morningSloteStart >= $startDate) {
//No date will be changed
if($endDate > $nightSloteStart) {
//i.e. 2.30 AM - 11.30 PM
if($morningSloteStart > $startDate) {
$nightSession = ago($morningSloteStart,$startDate);
}
$morningSession = ago($morningSloteEnd,$morningSloteStart);
$nightSession += ago($endDate,$nightSloteStart);
} else if($endDate >= $morningSloteStart) {
//i.e. 2.30 AM - 6.30 AM
//i.e. 2.30 AM - 6.30 AM
$nightSession = ago($morningSloteStart,$startDate);
$morningSession = ago($endDate,$morningSloteStart);
} else {
$morningSession = 0;
$nightSession = ago($endDate,$startDate);
}
} else if($endDate >= $nightSloteEnd) {
//Date will be changed
if($morningSloteStart < $startDate && $endDate < $nightSloteStart) {
//23:30 - 22:30
$morningSloteStart = date("m/d/Y H:i:s", strtotime("+1 day".$morningSloteStart));
$morningSloteEnd = date("m/d/Y H:i:s", strtotime("+1 day".$morningSloteEnd));
$nightSloteStart = date("m/d/Y H:i:s", strtotime("+1 day".$nightSloteStart));
$nightSession = ago($morningSloteStart,$startDate);
$morningSession = ago($morningSloteStart,$morningSloteEnd);
$nightSession += ago($endDate,$nightSloteStart);
} else {
//Removing date addition
$endDate = date("m/d/Y H:i:s", strtotime("-1 day".$endDate));
//i.e. 11.30 PM - 6.00 AM && 6.00 AM - 6.20 PM
$nightSession = ago($startDate,$nightSloteEnd);
$morningSession = ago($endDate,$morningSloteStart);
}
} else {
if($startDate >= $morningSloteStart && $nightSloteStart >= $endDate) {
//i.e. 6.30 AM - 9.30 AM
$nightSession = 0;
$morningSession = ago($endDate,$startDate);
} else if($startDate >= $morningSloteStart && $nightSloteStart < $startDate) {
//i.e. 22.30 PM - 23.59
$nightSession = ago($startDate,$endDate);
$morningSession = 0;
} else if($startDate >= $morningSloteStart && $nightSloteStart < $endDate) {
//i.e. 5.30 PM - 23.59
$nightSession = ago($nightSloteStart,$endDate);
$morningSession = ago($startDate,$nightSloteStart);
} else {
//Date will be changed
//i.e. 11.30 PM - 6.00 AM && 6.00 AM - 2.30 AM
$morningSession = 0;
$nightSession = ago($endDate,$startDate);
}
}
}
}
$output["morningSession"] = $morningSession/60; //hours
$output["nightSession"] = $nightSession/60; //hours
return $output;
}
function ago($datetime1,$datetime2) {
$date1 = new DateTime($datetime1);
$date2 = new DateTime($datetime2);
$interval = $date1->diff($date2);
$minutes = 0;
if($interval->days >= 1) $minutes += $interval->days * 24 * 60;
if($interval->h >= 1) $minutes += $interval->h * 60;
if($interval->i >= 1) $minutes += $interval->i;
return $minutes;
}
?>

Related

How to know if the difference btw time is 20 minutes [duplicate]

How to calculate minute difference between two date-times in PHP?
The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm.
Eg.
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
$since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).
The above code will output:
1837 days total5 years0 months10 days6 hours14 minutes2 seconds
To get the total number of minutes:
$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';
This will output:
2645654 minutes
Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php
Here is the answer:
$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value

calculate if hour it´s in labor time [duplicate]

How to calculate minute difference between two date-times in PHP?
The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm.
Eg.
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
$since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).
The above code will output:
1837 days total5 years0 months10 days6 hours14 minutes2 seconds
To get the total number of minutes:
$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';
This will output:
2645654 minutes
Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php
Here is the answer:
$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value

PHP calculate difference in time [duplicate]

How to calculate minute difference between two date-times in PHP?
The answers above are for older versions of PHP. Use the DateTime class to do any date calculations now that PHP 5.3 is the norm.
Eg.
$start_date = new DateTime('2007-09-01 04:10:58');
$since_start = $start_date->diff(new DateTime('2012-09-11 10:25:00'));
echo $since_start->days.' days total<br>';
echo $since_start->y.' years<br>';
echo $since_start->m.' months<br>';
echo $since_start->d.' days<br>';
echo $since_start->h.' hours<br>';
echo $since_start->i.' minutes<br>';
echo $since_start->s.' seconds<br>';
$since_start is a DateInterval object. Note that the days property is available (because we used the diff method of the DateTime class to generate the DateInterval object).
The above code will output:
1837 days total5 years0 months10 days6 hours14 minutes2 seconds
To get the total number of minutes:
$minutes = $since_start->days * 24 * 60;
$minutes += $since_start->h * 60;
$minutes += $since_start->i;
echo $minutes.' minutes';
This will output:
2645654 minutes
Which is the actual number of minutes that has passed between the two dates. The DateTime class will take daylight saving (depending on timezone) into account where the "old way" won't. Read the manual about Date and Time http://www.php.net/manual/en/book.datetime.php
Here is the answer:
$to_time = strtotime("2008-12-13 10:42:00");
$from_time = strtotime("2008-12-13 10:21:00");
echo round(abs($to_time - $from_time) / 60,2). " minute";
Subtract the past most one from the future most one and divide by 60.
Times are done in Unix format so they're just a big number showing the number of seconds from January 1, 1970, 00:00:00 GMT
<?php
$date1 = time();
sleep(2000);
$date2 = time();
$mins = ($date2 - $date1) / 60;
echo $mins;
?>
<?php
$start = strtotime('12:01:00');
$end = strtotime('13:16:00');
$mins = ($end - $start) / 60;
echo $mins;
?>
Output:
75
It worked on my programs, i'am using date_diff, you can check date_diff manual on here.
$start = date_create('2015-01-26 12:01:00');
$end = date_create('2015-01-26 13:15:00');
$diff=date_diff($end,$start);
print_r($diff);
You get results what do you want.
DateTime::diff is cool, but awkward for this sort of calculations that require a single unit result. Manually subtracting the timestamps works better:
$date1 = new DateTime('2020-09-01 01:00:00');
$date2 = new DateTime('2021-09-01 14:00:00');
$diff_mins = abs($date1->getTimestamp() - $date2->getTimestamp()) / 60;
another way with timezone.
$start_date = new DateTime("2013-12-24 06:00:00",new DateTimeZone('Pacific/Nauru'));
$end_date = new DateTime("2013-12-24 06:45:00", new DateTimeZone('Pacific/Nauru'));
$interval = $start_date->diff($end_date);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
I wrote this function for one my blog site(difference between a past date and server's date). It will give you an output like this
"49 seconds ago", "20 minutes ago", "21 hours ago" and so on
I have used a function that would get me the difference between the date passed and the server's date.
<?php
//Code written by purpledesign.in Jan 2014
function dateDiff($date)
{
$mydate= date("Y-m-d H:i:s");
$theDiff="";
//echo $mydate;//2014-06-06 21:35:55
$datetime1 = date_create($date);
$datetime2 = date_create($mydate);
$interval = date_diff($datetime1, $datetime2);
//echo $interval->format('%s Seconds %i Minutes %h Hours %d days %m Months %y Year Ago')."<br>";
$min=$interval->format('%i');
$sec=$interval->format('%s');
$hour=$interval->format('%h');
$mon=$interval->format('%m');
$day=$interval->format('%d');
$year=$interval->format('%y');
if($interval->format('%i%h%d%m%y')=="00000") {
//echo $interval->format('%i%h%d%m%y')."<br>";
return $sec." Seconds";
} else if($interval->format('%h%d%m%y')=="0000"){
return $min." Minutes";
} else if($interval->format('%d%m%y')=="000"){
return $hour." Hours";
} else if($interval->format('%m%y')=="00"){
return $day." Days";
} else if($interval->format('%y')=="0"){
return $mon." Months";
} else{
return $year." Years";
}
}
?>
Save it as a file suppose "date.php". Call the function from another page like this
<?php
require('date.php');
$mydate='2014-11-14 21:35:55';
echo "The Difference between the server's date and $mydate is:<br> ";
echo dateDiff($mydate);
?>
Of course you can modify the function to pass two values.
I think this will help you
function calculate_time_span($date){
$seconds = strtotime(date('Y-m-d H:i:s')) - strtotime($date);
$months = floor($seconds / (3600*24*30));
$day = floor($seconds / (3600*24));
$hours = floor($seconds / 3600);
$mins = floor(($seconds - ($hours*3600)) / 60);
$secs = floor($seconds % 60);
if($seconds < 60)
$time = $secs." seconds ago";
else if($seconds < 60*60 )
$time = $mins." min ago";
else if($seconds < 24*60*60)
$time = $hours." hours ago";
else if($seconds < 24*60*60)
$time = $day." day ago";
else
$time = $months." month ago";
return $time;
}
This is how I displayed "xx times ago" in php > 5.2 .. here is more info on DateTime object
//Usage:
$pubDate = $row['rssfeed']['pubDates']; // e.g. this could be like 'Sun, 10 Nov 2013 14:26:00 GMT'
$diff = ago($pubDate); // output: 23 hrs ago
// Return the value of time different in "xx times ago" format
function ago($timestamp)
{
$today = new DateTime(date('y-m-d h:i:s')); // [2]
//$thatDay = new DateTime('Sun, 10 Nov 2013 14:26:00 GMT');
$thatDay = new DateTime($timestamp);
$dt = $today->diff($thatDay);
if ($dt->y > 0){
$number = $dt->y;
$unit = "year";
} else if ($dt->m > 0) {
$number = $dt->m;
$unit = "month";
} else if ($dt->d > 0) {
$number = $dt->d;
$unit = "day";
} else if ($dt->h > 0) {
$number = $dt->h;
$unit = "hour";
} else if ($dt->i > 0) {
$number = $dt->i;
$unit = "minute";
} else if ($dt->s > 0) {
$number = $dt->s;
$unit = "second";
}
$unit .= $number > 1 ? "s" : "";
$ret = $number." ".$unit." "."ago";
return $ret;
}
function date_getFullTimeDifference( $start, $end )
{
$uts['start'] = strtotime( $start );
$uts['end'] = strtotime( $end );
if( $uts['start']!==-1 && $uts['end']!==-1 )
{
if( $uts['end'] >= $uts['start'] )
{
$diff = $uts['end'] - $uts['start'];
if( $years=intval((floor($diff/31104000))) )
$diff = $diff % 31104000;
if( $months=intval((floor($diff/2592000))) )
$diff = $diff % 2592000;
if( $days=intval((floor($diff/86400))) )
$diff = $diff % 86400;
if( $hours=intval((floor($diff/3600))) )
$diff = $diff % 3600;
if( $minutes=intval((floor($diff/60))) )
$diff = $diff % 60;
$diff = intval( $diff );
return( array('years'=>$years,'months'=>$months,'days'=>$days, 'hours'=>$hours, 'minutes'=>$minutes, 'seconds'=>$diff) );
}
else
{
echo "Ending date/time is earlier than the start date/time";
}
}
else
{
echo "Invalid date/time data detected";
}
}
A more universal version that returns result in days, hours, minutes or seconds including fractions/decimals:
function DateDiffInterval($sDate1, $sDate2, $sUnit='H') {
//subtract $sDate2-$sDate1 and return the difference in $sUnit (Days,Hours,Minutes,Seconds)
$nInterval = strtotime($sDate2) - strtotime($sDate1);
if ($sUnit=='D') { // days
$nInterval = $nInterval/60/60/24;
} else if ($sUnit=='H') { // hours
$nInterval = $nInterval/60/60;
} else if ($sUnit=='M') { // minutes
$nInterval = $nInterval/60;
} else if ($sUnit=='S') { // seconds
}
return $nInterval;
} //DateDiffInterval
Subtract the times and divide by 60.
Here is an example which calculate elapsed time from 2019/02/01 10:23:45 in minutes:
$diff_time=(strtotime(date("Y/m/d H:i:s"))-strtotime("2019/02/01 10:23:45"))/60;
My solution to find the difference between two dates is here. With this function you can find differences like seconds, minutes, hours, days, years and months.
function alihan_diff_dates($date = null, $diff = "minutes") {
$start_date = new DateTime($date);
$since_start = $start_date->diff(new DateTime( date('Y-m-d H:i:s') )); // date now
print_r($since_start);
switch ($diff) {
case 'seconds':
return $since_start->s;
break;
case 'minutes':
return $since_start->i;
break;
case 'hours':
return $since_start->h;
break;
case 'days':
return $since_start->d;
break;
default:
# code...
break;
}
}
You can develop this function. I tested and works for me. DateInterval object output is here:
/*
DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 0 [i] => 5 [s] => 13 [f] => 0 [weekday] => 0 [weekday_behavior] => 0 [first_last_day_of] => 0 [invert] => 0 [days] => 0 [special_type] => 0 [special_amount] => 0 [have_weekday_relative] => 0 [have_special_relative] => 0 )
*/
Function Usage:
$date = the past date,
$diff = type eg: "minutes", "days", "seconds"
$diff_mins = alihan_diff_dates("2019-03-24 13:24:19", "minutes");
Good Luck.
$date1=date_create("2020-03-15");
$date2=date_create("2020-12-12");
$diff=date_diff($date1,$date2);
echo $diff->format("%R%a days");
For detailed format specifiers, visit the link.
Another simple way to calculate the difference in minutes. Please note this is a sample for calculating within a 1-year range. for more details click here
$origin = new DateTime('2021-02-10 09:46:32');
$target = new DateTime('2021-02-11 09:46:32');
$interval = $origin->diff($target);
echo (($interval->format('%d')*24) + $interval->format('%h'))*60; //1440 (difference in minutes)
This will help....
function get_time($date,$nosuffix=''){
$datetime = new DateTime($date);
$interval = date_create('now')->diff( $datetime );
if(empty($nosuffix))$suffix = ( $interval->invert ? ' ago' : '' );
else $suffix='';
//return $interval->y;
if($interval->y >=1) {$count = date(VDATE, strtotime($date)); $text = '';}
elseif($interval->m >=1) {$count = date('M d', strtotime($date)); $text = '';}
elseif($interval->d >=1) {$count = $interval->d; $text = 'day';}
elseif($interval->h >=1) {$count = $interval->h; $text = 'hour';}
elseif($interval->i >=1) {$count = $interval->i; $text = 'minute';}
elseif($interval->s ==0) {$count = 'Just Now'; $text = '';}
else {$count = $interval->s; $text = 'second';}
if(empty($text)) return '<i class="fa fa-clock-o"></i> '.$count;
return '<i class="fa fa-clock-o"></i> '.$count.(($count ==1)?(" $text"):(" ${text}s")).' '.$suffix;
}
I found so many solution but I never got correct solution. But i have created some code to find minutes please check it.
<?php
$time1 = "23:58";
$time2 = "01:00";
$time1 = explode(':',$time1);
$time2 = explode(':',$time2);
$hours1 = $time1[0];
$hours2 = $time2[0];
$mins1 = $time1[1];
$mins2 = $time2[1];
$hours = $hours2 - $hours1;
$mins = 0;
if($hours < 0)
{
$hours = 24 + $hours;
}
if($mins2 >= $mins1) {
$mins = $mins2 - $mins1;
}
else {
$mins = ($mins2 + 60) - $mins1;
$hours--;
}
if($mins < 9)
{
$mins = str_pad($mins, 2, '0', STR_PAD_LEFT);
}
if($hours < 9)
{
$hours =str_pad($hours, 2, '0', STR_PAD_LEFT);
}
echo $hours.':'.$mins;
?>
It gives output in hours and minutes for example 01 hour 02 minutes like 01:02
Here is a simple one-liner:
$start = new DateTime('yesterday');
$end = new DateTime('now');
$diffInMinutes = iterator_count(new \DatePeriod($start, new \DateInterval('PT1M'), $end));
try this
$now = \Carbon\Carbon::now()->toDateString(); // get current time
$a = strtotime("2012-09-21 12:12:22");
$b = strtotime($now);
$minutes = ceil(($a - $b) / 3600); it will get ceiling value

Show x time ago if time is less than 24 hour ago

I use Codeigniter and it has the timespan() function that returns the time as 1 Year, 10 Months, 2 Weeks, 5 Days, 10 Hours, 16 Minutes.
What I'd like to do is only show the time formatted in x hours ago if the time is within the last 24 hours, otherwise just show a normal datetime.
I feel like there's got to be a function already made to do this but I haven't had any luck finding it.
This is the timespan function included with Codeigniter, how can I alter it?
/**
* Timespan
*
* Returns a span of seconds in this format:
* 10 days 14 hours 36 minutes 47 seconds
*
* #access public
* #param integer a number of seconds
* #param integer Unix timestamp
* #return integer
*/
if ( ! function_exists('timespan'))
{
function timespan($seconds = 1, $time = '')
{
$CI =& get_instance();
$CI->lang->load('date');
if ( ! is_numeric($seconds))
{
$seconds = 1;
}
if ( ! is_numeric($time))
{
$time = time();
}
if ($time <= $seconds)
{
$seconds = 1;
}
else
{
$seconds = $time - $seconds;
}
$str = '';
$years = floor($seconds / 31536000);
if ($years > 0)
{
$str .= $years.' '.$CI->lang->line((($years > 1) ? 'date_years' : 'date_year')).', ';
}
$seconds -= $years * 31536000;
$months = floor($seconds / 2628000);
if ($years > 0 OR $months > 0)
{
if ($months > 0)
{
$str .= $months.' '.$CI->lang->line((($months > 1) ? 'date_months' : 'date_month')).', ';
}
$seconds -= $months * 2628000;
}
$weeks = floor($seconds / 604800);
if ($years > 0 OR $months > 0 OR $weeks > 0)
{
if ($weeks > 0)
{
$str .= $weeks.' '.$CI->lang->line((($weeks > 1) ? 'date_weeks' : 'date_week')).', ';
}
$seconds -= $weeks * 604800;
}
$days = floor($seconds / 86400);
if ($months > 0 OR $weeks > 0 OR $days > 0)
{
if ($days > 0)
{
$str .= $days.' '.$CI->lang->line((($days > 1) ? 'date_days' : 'date_day')).', ';
}
$seconds -= $days * 86400;
}
$hours = floor($seconds / 3600);
if ($days > 0 OR $hours > 0)
{
if ($hours > 0)
{
$str .= $hours.' '.$CI->lang->line((($hours > 1) ? 'date_hours' : 'date_hour')).', ';
}
$seconds -= $hours * 3600;
}
$minutes = floor($seconds / 60);
if ($days > 0 OR $hours > 0 OR $minutes > 0)
{
if ($minutes > 0)
{
$str .= $minutes.' '.$CI->lang->line((($minutes > 1) ? 'date_minutes' : 'date_minute')).', ';
}
$seconds -= $minutes * 60;
}
if ($str == '')
{
$str .= $seconds.' '.$CI->lang->line((($seconds > 1) ? 'date_seconds' : 'date_second')).', ';
}
return substr(trim($str), 0, -1);
}
}
This function will accept a string, a numeric (unix) timestamp, or a DateTime object. It also accepts jQuery.now(). Time may be in the future or past.
function time_ago($time=false, $just_now=false) {
if ($time instanceOf DateTime)
$time = $time->getTimestamp();
elseif (is_numeric($time))
$time = date('m/d/y h:i A', $time);
if (strtotime($time) === false)
$time = date('m/d/y h:i A', time());
$interval = date_create($time)->diff(date_create('now'));
$adjective = strtotime($time) > time() ? 'from now' : 'ago';
return (
$interval->days > 0 ?
$time : (
$interval->h < 1 && $interval->i < 1 && $just_now ?
'just now' :
(
$interval->h > 1 ?
$interval->h.' hour'.(
$interval->h > 1 ?
's' :
''
).' ago' :
$interval->i.' minutes'.' '.$adjective
)
)
);
}
echo time_ago('8/22/2012 5:00 PM'); // 3 hours ago
echo time_ago('8/21/2012 5:00 PM'); // 8/21/2012 5:00 PM
echo time_ago(time()); // 0 hours ago
echo time_ago(time(), true); // just now
echo time_ago(strtotime('5 days ago')); // 08/17/12 08:18 PM
echo time_ago(strtotime('5 hours ago')); // 5 hours ago
echo time_ago(strtotime('5 minutes ago')); // 5 minutes ago
echo time_ago(strtotime('+5 minutes')); // 5 minutes from now
echo time_ago('jQuery.now()', true); // just now
echo time_ago('sweet explosions, bro!', true); // just now
Documentation
date - http://php.net/manual/en/function.date.php
DateTime object - http://www.php.net/manual/en/book.datetime.php
DateInterval object - http://www.php.net/manual/en/class.dateinterval.php
is_numeric - http://php.net/manual/en/function.is-numeric.php
if( time() - $yourTime <= 86400 ) { // 86400 seconds in a day
echo timespan($yourTime);
} else {
echo date('m/d/Y \a\t H:i:s', $yourTime);
}
Don't rely on a framework, especially a bad one, for everything!
Fiddle with $format to suit your needs. Will accept almost anything as input.
<?php
/**
* RelativeTime - pretty printed
* #author Dejan Marjanovic
*/
class Site5_RelativeTime
{
private $interval = '';
public function __construct()
{
call_user_func_array(array($this, 'calculate'), func_get_args());
}
public function calculate($start, $end = NULL)
{
if ( empty($start))
return false;
if (empty($end))
$end = time();
if ( ! is_numeric($start))
$start = strtotime($start);
if ( ! is_numeric($end))
$end = strtotime($end);
if($start > $end)
$future = TRUE;
$start = '#' . $start;
$end = '#' . $end;
if ( ! ($start instanceof DateTime))
$start = new DateTime($start);
if ($end === null)
$end = new DateTime();
if ( ! ($end instanceof DateTime))
$end = new DateTime($end);
$interval = $end->diff($start);
$get_plural = function($int, $str)
{
return $int > 1? $str.'s': $str;
};
$format = array();
if ($interval->y !== 0)
$format[] = "%y " . $get_plural($interval->y, "year");
if ($interval->m !== 0)
$format[] = "%m " . $get_plural($interval->m, "month");
if ($interval->d !== 0)
$format[] = "%d " . $get_plural($interval->d, "day");
if ($interval->h !== 0)
$format[] = "%h " . $get_plural($interval->h, "hour");
if ($interval->i !== 0)
$format[] = "%i " . $get_plural($interval->i, "minute");
if ($interval->s !== 0)
{
if ( ! count($format))
{
$this->interval = "less than a minute";
return;
}
else
{
$format[] = "%s " . $get_plural($interval->s, "second");
}
}
if (count($format) > 1)
{
$format = array_shift($format) . " and " . array_shift($format);
}
else
{
$format = array_pop($format);
}
$tense = ($future === TRUE)? 'from now': 'ago';
$this->interval = $interval->format($format) . ' ' . $tense;
}
public function __toString()
{
return $this->interval;
}
}

PHP How do I calculate relative time? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
PHP: producing relative date/time from timestamps
Given a specific DateTime value, how do I display relative time, like
35 minutes ago
2 hours ago
3 days ago
1 month ago
etc, etc...?
mysql_query("UPDATE users SET lastlogin = ".time()." WHERE id = ".$userID);
this may help you
function time_ago_en($time)
{
if(!is_numeric($time))
$time = strtotime($time);
$periods = array("second", "minute", "hour", "day", "week", "month", "year", "age");
$lengths = array("60","60","24","7","4.35","12","100");
$now = time();
$difference = $now - $time;
if ($difference <= 10 && $difference >= 0)
return $tense = 'just now';
elseif($difference > 0)
$tense = 'ago';
elseif($difference < 0)
$tense = 'later';
for($j = 0; $difference >= $lengths[$j] && $j < count($lengths)-1; $j++) {
$difference /= $lengths[$j];
}
$difference = round($difference);
$period = $periods[$j] . ($difference >1 ? 's' :'');
return "{$difference} {$period} {$tense} ";
}
Usage:
<?php
echo time_ago_en(time() - 300); // 5 minutes ago
?>
strtotime is a nice function
let me be more specific
strtotime(-5 days);
or
strtotime(-1 month);
There is an optional 2nd argument which is another time stamp of the time you want to start at, giving your relative time. Why the downvote?
<?php
function relativeTime($time = false, $limit = 86400, $format = 'g:i A M jS') {
if (empty($time) || (!is_string($time) && !is_numeric($time))) $time = time();
elseif (is_string($time)) $time = strtotime($time);
$now = time();
$relative = '';
if ($time === $now) $relative = 'now';
elseif ($time > $now) $relative = 'in the future';
else {
$diff = $now - $time;
if ($diff >= $limit) $relative = date($format, $time);
elseif ($diff < 60) {
$relative = 'less than one minute ago';
} elseif (($minutes = ceil($diff/60)) < 60) {
$relative = $minutes.' minute'.(((int)$minutes === 1) ? '' : 's').' ago';
} else {
$hours = ceil($diff/3600);
$relative = 'about '.$hours.' hour'.(((int)$hours === 1) ? '' : 's').' ago';
}
}
return $relative;
}
?>
Source

Categories