I am working out the months, days, hours and minutes between two dates, I have successfully got it to work out the months, days and minutes, but I cannot for the life of get it to work out the minutes, below is my code.
<?php
$date1 = "2012-07-01 00:00:00";
$date2 = "2012-09-30 00:00:00";
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24));
$months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24));
$days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$minutes = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24) / (60*60*24) / (60*60));
printf("%d years, %d months, %d days, %d minutes\n", $years, $months, $days, $minutes);
?>
The best and most accurate way to approach this problem is to use the DateTime class. Otherwise you'll run into issues when you deal with anomalies in dates (leap year, etc).
$format = 'Y-m-d h:i:s';
$tz = new DateTimeZone('America/New_York');
// Create DateTime objs based on the above format
$t1 = DateTime::createFromFormat( $format, "2012-07-01 00:00:00", $tz);
$t2 = DateTime::createFromFormat( $format, "2012-09-30 00:00:00", $tz);
// Find the difference between them
$diff = $t1->diff( $t2);
// Print out the difference in each amount
$outputs = array( 'Y' => 'Year', 'm' => 'Month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'seconds');
foreach( $outputs as $key => $value)
echo $diff->format( '%'.$key) . ' ' . $value . "\n";
This outputs:
00 Year
2 Month
29 day
0 hour
0 minute
0 seconds
Try reducing your $diff variable as you work everything else out:
$years = floor($diff / 31557600); // 31557600 = 365.25 * 86400
$diff -= $years * 31557600;
// I'd skip months, since different months have a different number of days.
// If you *really* want it, calculate the number of months from the days below.
$days = floor($diff / 86400); // 86400 = 24 * 3600
$diff -= $days * 86400;
$hours = floor($diff / 3600); // 3600 = 60 * 60
$diff -= $days * 3600;
$minutes = floor($diff / 60);
$diff -= $minutes * 60;
// $diff now equals the number of seconds left over
Alternatively, look into PHP's Date/Time object:
$date1 = new DateTime("2012-07-01 00:00:00");
$date2 = new DateTime("2012-09-30 00:00:00");
$diff = $date1->diff($date2); // $diff is a DateInterval object
Look at DateInterval->format() to determine how you want to format your output from $diff.
Used to have one of the following functions, to convert seconds into days/weeks/hh:mm:ss time etc.
That should answer your query.
function duration ($sec, $padHours = false) {
if ($sec > 1209600) return "> ". intval(intval($sec) / 604800) . " weeks";
if ($sec > 604800) return "1 week";
if ($sec > 172800) return "> ". intval(intval($sec) / 86400) . " days";
if ($sec > 86400) return "1 day";
$hms = "";
$hours = intval(intval($sec) / 3600);
$hms .= ($padHours)
? str_pad($hours, 2, "0", STR_PAD_LEFT). ":"
: $hours. ":";
$minutes = intval(($sec / 60) % 60);
$hms .= str_pad($minutes, 2, "0", STR_PAD_LEFT). ":";
$seconds = intval($sec % 60);
$hms .= str_pad($seconds, 2, "0", STR_PAD_LEFT);
return $hms;
}
Related
I am trying to find the time difference between 2 timestamps.
Timestamp "startTime" have 1601096400
Timestamp "expireTime" have 1601094600
I want to output the difference between both time like
Expire in : 4hr 30min
How do I do it in php ?
You can use this function
function timestamp_diff($a,$b){
$datetime1 = new DateTime($a);
$datetime2 = new DateTime($b);
$interval = $datetime1->diff($datetime2);
$d=$interval->format('%a');
$h=$interval->format('%h');
$m=$interval->format('%i');
return 'Expire in :'.$d.'day and '.$h.'hr'.$m.'min'
}
Try This is work proper.
<?php
$diff = 1601096400 - 1601094600;
//if use date so try this
$diff = strtotime("2020-09-26 08:10:00") - strtotime("2020-10-26 04:42:00");
$days = floor($diff / 86400);
$hours = floor(($diff - ($days * 86400)) / 3600);
$minutes = floor(($diff - ($days * 86400) - ($hours * 3600))/60);
$seconds = floor(($diff - ($days * 86400) - ($hours * 3600) - ($minutes*60)));
echo 'Expire in : '$hours.'hr'.$minutes.'min';
?>
I have a PHP and MySQL code that should calculate the hours minutes and days of difference between two date and hours. It works well, just adding 20 hours and 20 minutes more than normal. And I remove the DATE part and put the date and time manually, it works fine.
I don't understand what happens.
$fecha = $row["fecha"];
$data= $row["hora"];
$start = strtotime("$fecha $hora");
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate = date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));
$end = strtotime("$currentDate");
$totaltime = ($end - $start) ;
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == Start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}
Edit
start 2019-12-29 21:27:50 . end 2019-12-31 0:51:50 = 47:51:16
As you can see it calculates badly.
A simple example like this would do the job :
$mydatetime = new DateTime();
$datefromdb = new DateTime('2018-03-05 10:10:00');
$interval = $mydatetime->diff($datefromdb);
$date_count = $interval->format('%y years %m months %a days %h hours %i minutes %s seconds');
echo $date_count;
This is your code it should work
$fecha = $row["fecha"];
$data= $row["hora"];
$start = strtotime("$fecha $data");
$currentDate = date("Y-m-d");
$currentTime = date("H:i:s");
$currentDate = date("Y-m-d H:i:s", strtotime($currentDate .$currentTime));
$end = strtotime("$currentDate");
$totaltime = ($end - $start) ;
$hours = intval($totaltime / 3600);
$seconds_remain = ($totaltime - ($hours * 3600));
$minutes = intval($seconds_remain / 60);
$seconds = ($seconds_remain - ($minutes * 60));
$statusfichaje= $row["status"];
if ($statusfichaje == $start){echo '<td>Trabajando'.$hours.':'.$minutes.':'.$seconds.' </td>';}else{echo '<td>'. $row["status"] .'</td>';}
problem was in the string.
$data= $row["hora"];
and I use this
$start = strtotime("$fecha $hora");
And don't take the hours and calculate only for days.
Thank you
I'm trying to get the difference between two date-times and return it as a minute. Date & Time are taken in date("Y-m-d H:i:s") format. But it seem i can't get it right. I did it
$time=date("Y-m-d H:i:s");
$time=date("2014-01-13 08:18:25");
$interval = $time->diff($login_time);
$elapsed = $interval->format(%i minutes);
echo $elapsed;
And This is showing a massage
"Call to a member function diff() on a non-object"
As I am not good enough with date formatting. So Please help me.
What is the way to go about this?
Try this:
$date1 = new DateTime('2013-01-13 04:10:58');
$datediff = $date1->diff(new DateTime('2013-09-11 10:25:00'));
echo $datediff->i;
For more details see this link : http://www.php.net/manual/en/book.datetime.php
Get difference is minutes between two dates:
$now = new DateTime;
$before = new DateTime('2014-01-10 08:18:25');
$diff = $now->diff($before);
$elapsed = $diff->days * 24 * 60 + $diff->h * 60 + $diff->i;
demo
Use the below code for getting time in all expected parameter.
$time1=date("Y-m-d H:i:s");
$time2=date("2014-01-13 08:18:25");
$seconds = strtotime($time1) - strtotime($start);
$year = floor(($seconds)/(60*60*24*365)); $months = floor($seconds /
86400 / 30 ); $week = floor($seconds / 604800); $days =
floor($seconds / 86400); $hours = floor(($seconds - ($days * 86400))
/ 3600); $minutes = floor(($seconds - ($days * 86400) - ($hours *
3600))/60); $seconds = floor(($seconds - ($days * 86400) - ($hours *
3600) - ($minutes*60)));
$time1 = "01:00";
$time2 = "04:55";
list($hours1, $minutes1) = explode(':', $time1);
$startTimestamp = mktime($hours1, $minutes1);
list($hours2, $minutes2) = explode(':', $time2);
$endTimestamp = mktime($hours2, $minutes2);
$seconds = $endTimestamp - $startTimestamp;
$minutes = ($seconds / 60) % 60;
$hours = round($seconds / (60 * 60));
echo $hours.':'.$minutes;
exit;
Outputs 4:55, should be 3:55 ?
Whats wrong here? If it is 01:00 and 02:00, it works fine, but not with the above?
Use floor instead of round...
Or just cast to integer.
$hours = (int) ($seconds / (60 * 60));
Too many calculations when PHP can do it for you with also reducing possibility of error
$time1 = Datetime::createFromFormat("h:i", "01:00");
$time2 = Datetime::createFromFormat("h:i", "04:55");
$diff = $time1->diff($time2);
var_dump($diff->format("%h %i"));
Output
string '3:55' (length=4)
You can also save yourself some time by using strtotime:
$time1 = strtotime("01:00");
$time2 = strtotime("04:55");
$seconds = $time2-$time1;
$minutes = ($seconds / 60) % 60;
$hours = floor($seconds / (60 * 60));
echo $hours.':'.$minutes;
As mentioned, using floor will produce the result you need:
Result
3:55
I want to subtract one date to another using php and display result in the days - hours - min - sec format. How i do this using php . I tried this using time stamp but it does not give proper values. please give suggestion
For ex : from date 2012-04-27 19:30:56 to date 2012-04-27 19:37:56
i used this code
if(strtotime($history['datetimestamp']) > strtotime($lasttime)) {
$totalelapsed1 = (strtotime($history['datetimestamp'])-strtotime($lasttime));
if($totalelapsed1 > 60 ) {
$sec = $totalelapsed1%60;
$min = round($totalelapsed1/60 , 0);
$minute = $min + $minute;
$second = $sec + $second;
// echo $min. " min " .$sec." sec";
} else {
//echo "0 min " . $totalelapsed1." sec";
$minute = 0 + $minute;
$second = $totalelapsed1 + $second;
}
} else {
$minute = 0 + $minute;
$second = 0 + $second;
// echo "0 min 0 sec";
}
From how to subtract two dates and times to get difference by VolkerK:
You have to use like this:-
<?php
//$now = new DateTime(); // current date/time
$now = new DateTime("2010-07-28 01:11:50");
$ref = new DateTime("2010-07-30 05:56:40");
$diff = $now->diff($ref);
printf('%d days, %d hours, %d minutes', $diff->d, $diff->h, $diff->i);
prints 2 days, 4 hours, 44 minutes
see http://docs.php.net/datetime.diff
edit: But you could also shift the problem more to the database side, e.g. by storing the expiration date/time in the table and then do a query like
... WHERE key='7gedufgweufg' AND expires<Now()
Many rdbms have reasonable/good support for date/time arithmetic.
Link Url:- how to subtract two dates and times to get difference
http://www.webpronews.com/calculating-the-difference-between-two-dates-using-php-2005-11
I suggest to use DateTime and DateInterval objects.
$date1 = new DateTime("2007-03-24");
$date2 = new DateTime("2009-06-26");
$interval = $date1->diff($date2);
echo "days difference ".$interval->d." days ";
read more php DateTime::diff manual
Try using DateTime:diff().
Examples are provided on that page.
This script resolve my issue
$date1 = date("d-m-Y H:i:s",strtotime($date1));
$date2 = date("d-m-Y H:i:s",strtotime($lasttime));
$diff = abs(strtotime($date2) - strtotime($date1));
$years = floor($diff / (365*60*60*24)); $months = floor(($diff - $years * 365*60*60*24) / (30*60*60*24)); $days = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24)/ (60*60*24));
$hours = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24)/ (60*60)); $minuts = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60)/ 60); $seconds = floor(($diff - $years * 365*60*60*24 - $months*30*60*60*24 - $days*60*60*24 - $hours*60*60 - $minuts*60));
printf("%d years, %d months, %d days, %d hours, %d minuts\n, %d seconds\n", $years, $months, $days, $hours, $minuts, $seconds);