I have two data inputs where you can enter start time and finish time.
for example
start_time 13:00
finish_time 14:40
The entry wil开发者_开发知识库l be always the format of HH:MM.
I'd like to find the time difference, in this case 100 minutes.
What is the best way to do it?
You could use diff within DateTime.
#!/usr/bin/env php
<?php
$datetime1 = new DateTime('13:00');
$datetime2 = new DateTime('14:40');
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo $hours * 60 + $minutes;
?>
You can use strtotime to get a timestamp from a string then get the difference from the timestamps, after that converting to a date or time formatted in minutes is easy.
Ex.
<?php
$start = "26 Sep, 2010 13:00";
$end = "26 Sep, 2010 14:40";
$timeStart = strtotime($start);
$timeEnd = strtotime($end);
$diff = ($timeEnd - $timeStart);
echo "Minutes : " . ($diff / 60) . "<br />";
echo "Date : " . date("j M, Y h:i:s a", $diff); //This would end up being the
//Years, months, days, hours, etc it took to complete the task.
?>
If you wanted a function, so you can make this kind of calculation multiple times in a single script:
/**
* get_time_difference
*
* @param string start time
* @param string finish time
* @return int time difference in minutes, rounded up
*/
function get_time_difference($start, $finish)
{
return ceil(abs((strtotime($finish) - strtotime($start)) / 60));
}
$start_time = '13:00';
$finish_time = '14:40';
$diff = get_time_difference($start_time, $finish_time);
echo $diff; // 100
Note the use of the ceil()
function (rounds up) to avoid any decimal answers.
If we are talking about PHP - the time in PHP is represented as unixtime - number of seconds since epoch (1 Jan 1970). So you need to just substruct one time from another and you will get the difference in seconds.
If the time in php is in textual representation - you can convert it to unixtime by calling strtotime beforehand.
Well, let's assume that you have two strings in HH:MM format; $time1
and $time2
say. I'm going to assume that $time1
and $time2
refer to times on the same day in the same time zone (unless $time1
is after $time2
, in which case I'll assume that $time2
is the day after $time1
).
$time1 = explode(':', $time1);
$time2 = explode(':', $time2);
$time1_hours = intval($time1[0], 10);
$time1_mins = intval($time1[1], 10);
$time2_hours = intval($time2[0], 10);
$time2_mins = intval($time2[1], 10);
$time1_mins_past_midnight = 60 * $time1_hours + $time1_mins;
$time2_mins_past_midnight = 60 * $time2_hours + $time2_mins;
$time_difference = ( $time1_mins_past_midnight > $time2_mins_past_midnight ) ?
1440 + $time2_mins_past_midnight - $time1_mins_past_midnight :
$time2_mins_past_midnight - $time1_mins_past_midnight;
Now $time_difference
contains the time difference, in minutes.
Check out How to get time difference in minutes in PHP.
精彩评论