How can I calculate time duration considering the datestamp in PHP? the date format I used in between dates is "Y-m-d H:i:s",
My working code can only compute the duration between time without considering the date.
below is my code:
$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";
function hmsDiff ($assigned_time, $completed_time) {
$assigned_seconds = hmsToSeconds($assigned_time);
$completed_seconds = hmsToSeconds($completed_time);
$remaining_seconds = $assigned_seconds - $completed_seconds;
return secondsToHMS($remaining_seconds);
}
function hmsToSeconds ($hms) {
$total_seconds = 0;
list($hours, $minutes, $seconds) = explode(":", $hms);
$total_seconds += $hours * 60 * 60;
$total_seconds += $minutes * 60;
$total_seconds += $seconds;
return $total_seconds;
}
function secondsToHMS ($seconds) {
$minutes = (int)($seconds / 60);
$seconds = $seconds % 60;
$hours = (int)($minutes / 60);
$minutes = $minutes % 60;
return sprintf("%02d", abs($hours)) . ":" .
sprintf("%02d", abs($minutes)) . ":" .
sprintf("%02d", abs($seconds));
}
The DateTime has a "diff" method which returns an Interval object. The interval object has a method "format" which allows you to customize the output.
#!/usr/bin/env php
<?php
$assigned_time = "2012-05-21 22:02:00";
$completed_time= "2012-05-22 05:02:00";
$d1 = new DateTime($assigned_time);
$d2 = new DateTime($completed_time);
$interval = $d2->diff($d1);
echo $interval->format('%d days, %H hours, %I minutes, %S seconds');
NOTE: If you are not using 5.3.0+, there is a good answer here: https://stackoverflow.com/a/676828/128346.
Not completely knowing what you want, what about something like:
// prevents php error
date_default_timezone_set ( 'US/Eastern' );
// convert to time in seconds
$assigned_seconds = strtotime ( $assigned_time );
$completed_seconds = strtotime ( $completed_time );
$duration = $completed_seconds - $assigned_seconds;
// j gives days
$time = date ( 'j g:i:s', $duration );
Related
Currently, I have data as below. But, it wasn't a timestamp value. It was a time itself
$start_time = '150630';
$end_time = '180630';
I want to change the format like 03:06 PM – 06:06 PM i tried
$init = 150630;
$hours = floor($init / 3600);
$minutes = floor(($init / 60) % 60);
$seconds = $init % 60;
echo "$hours:$minutes:$seconds";
But the format and value is not as expected.
Please help me how to solve this
You doesn't need time converter as your string wasn't a valid timestamp. Instead, it was time itself. You just need to extract the hour, min, and second.
Refer below
<?php
$start_time = "150630";
$hours = substr($start_time, 0, 2); // this is actual hours
$mins = substr($start_time, 2, 2); // this is actual minutes
$secs = substr($start_time, 4, 2); // this is actual seconds
if ($hours < 12) {
$actTime = "$hours:$mins:$secs AM";
} else {
$actTime = ($hours-12).":$mins:$secs PM";
}
echo $actTime; // this is the time format you want
You can use str_split function as your time format is not timestamp.
It will extract hours, minutes and seconds.
check the below code :
<?php
$start_time = '150630';
$end_time = '180630';
$startTimeA = str_split($start_time, 2);
$endTimeA = str_split($end_time, 2);
$startTime = "";
$AmOrPm = "AM";
if ($startTimeA[0] > 12) {
$startTime .= (int) ($startTimeA[0] - 12);
$AmOrPm = "PM";
}
echo $startTime .= ":" . $startTimeA[1] . " " . $AmOrPm;
$endTime = "";
$AmOrPm = "AM";
if ($endTimeA[0] > 12) {
$endTime .= (int) ($endTimeA[0] - 12);
$AmOrPm = "PM";
}
echo $endTime .= ":" . $endTimeA[1] . " " . $AmOrPm;
?>
Use Php Date Function And Strtotime
strtotime — Parse about any English textual datetime description into a Unix timestamp.
And Convert It like
echo $start_time = date('h:i:a' , strtotime(150630));
//o/p 03:06:pm
I'm trying to get the difference in time between two given times e.g. first time '17:00:01' and then second time '17:47:25' and here's what I tried so far,
$start_time = "17:00:01";
$end_time = "17:47:25";
echo $start_time->diff($end_time);
But seem's unfortunately not working, any help, ideas please?
My expected output must be like, if no difference in hours but there's difference in minutes and seconds then, "22 mins and 15 secs", If no difference in minutes but have difference in hours then, "2 hrs and 10 secs" but if only seconds in difference then, "22 secs".
Get difference between two times
public function convTimeToMinutes($intime, $outtime)
{
$start = Carbon::parse($intime);
$end = Carbon::parse($outtime);
$minutes = $end->diffInMinutes($start); // 226
return $this->convertMinuteToHours($minutes);
}
public function convertMinuteToHours($minutes)
{
return $minutes / 60;
}
$totalHour = $this->convTimeToMinutes('09:25:35', '13:12:27');
//$totalHour = 3.76
String in php is not object, so can't call diff method on it.
Use diff method, you must change the string to DateTime object.
If you want to compare time difference in same day, you could try:
$start_time = "17:00:01";
$end_time = "17:47:25";
$start_datetime = new DateTime(date('Y-m-d').' '.$start_time);
$end_datetime = new DateTime(date('Y-m-d').' '.$end_time);
var_dump($start_datetime->diff($end_datetime));
Here is it.
PHP
$start_time = "17:00:01";
$end_time = "17:47:25";
$time1 = new DateTime($start_time);
$time2 = new DateTime($end_time);
$interval = $time1->diff($time2);
echo $hour = $interval->format('%h hour');
echo $min = $interval->format('%i min');
echo $sec = $interval->format('%s second');
Output:
0 hour 47 min 24 sec
Now you can add some condition and make the real format.
Just another way of doing it using string functions:
/*
* Get difference in seconds between time formats
*/
function getDiff($start_time, $end_time)
{
$start_time = timeFormatToSeconds($start_time);
$end_time = timeFormatToSeconds($end_time);
if ($end_time > $start_time) {
return $end_time - $start_time;
}
return false;
}
/*
* Convert time format (HH:MM:SS) to seconds
*/
function timeFormatToSeconds($time_format)
{
sscanf($time_format, "%d:%d:%d", $hours, $minutes, $seconds);
return $hours * 3600 + $minutes * 60 + $seconds;
}
$start_time = "17:00:01";
$end_time = "17:47:25";
$diff = getDiff($start_time, $end_time);
if ($diff) {
$hours = floor($time / (60 * 60));
$time -= $hours * (60 * 60);
$minutes = floor($time / 60);
$time -= $minutes * 60;
$seconds = floor($time);
$time -= $seconds;
var_dump(array($hours, $minutes, $seconds));
}
Convert string time to timestamp and subtract. Convert timestamp to desired time format.
$start_time = strtotime('17:00:01');
$end_time = strtotime('17:47:25');
$diff = $end_time - $start_time;
echo date('H:i:s', $diff);
You can do something like this as a generic function
private function calculateDiffInMinutes($from, $to)
{
$from = Carbon::createFromFormat('Y-m-d H:s:i', $from);
$to = Carbon::createFromFormat('Y-m-d H:s:i', $to);
return $to->diffInMinutes($from);
}
and you can call the function anywhere and pass the parameters you need
here the difference between now and created at time
$this->calculateDiffInMinutes($item->created_at, now())
Hope this helped
I tried this:
$total_time_minutes = '132';
$total_time_hours = '26';
if($total_time_minutes > 60)
{
$time = strtotime( $minutes . ' minutes');
$time = date('H:i', $time);
$time = explode(':', $time);
$hours = $time[0];
$minutes = $time[1];
$total_time_hours += $hours;
$total_time_minutes = $minutes;
}
if i output $total_time_hours and $total_time_minutes from this it will give me: 26:44, which is incorrect.
It should give me 28:12, what's wrong here?
$total_time_minutes = '132';
$total_time_hours = '26';
if($total_time_minutes > 60)
{
$hours = floor($total_time_minutes / 60);
$minutes = $total_time_minutes % 60;
$total_time_hours += $hours;
$total_time_minutes = $minutes;
}
date() function if for unix timestamp formatting. What you have is not a valid unix timestamp (yes, I understand it could be that small, but not in this particular case)
Got this working on php 5.3
$datetime1 = new DateTime("2011-10-10 10:00:00");
$datetime2 = new DateTime("2011-10-10 10:45:00");
$interval = $datetime1->diff($datetime2);
$hours = $interval->format('%h');
$minutes = $interval->format('%i');
echo 'Diff. in minutes is: '.($hours * 60 + $minutes);
How can i make it work on php 5.2 ? are there any equivalent functions available??
Got it working
$date1 = "2011-10-10 10:00:00";
$date2 = "2011-10-10 10:11:00";
echo round((strtotime($date2) - strtotime($date1)) /60);
Instead of DateTime you can use strtotime and date:
$datetime1 = strtotime("2011-10-10 10:00:00");
$datetime2 = strtotime("2011-10-10 10:45:00");
$interval = abs($datetime2 - $datetime1);
$minutes = round($interval / 60);
echo 'Diff. in minutes is: '.$minutes;
If you need the minutes spanning several days you could add this one into the mix:
$days = $interval->format("%d");
if ($days > 0) {
return ($hours * 60 + $minutes) + ($days * 24 * 60);
}
Try this
function time_Diff_Minutes($startTime, $endTime) {
$to_time = strtotime($endTime);
$from_time = strtotime($startTime);
$minutes = ($to_time - $from_time) / 60;
return ($minutes < 0 ? 0 : abs($minutes));
}
echo time_Diff_Minutes("2008-12-13 20:00:00","2008-12-14 08:00:00"); //output 720
echo time_Diff_Minutes("2008-12-14 20:00:00","2008-12-13 08:00:00"); //output 0 (startTime > endTime) Ternary will return 0
How to turn time in format HH:MM:SS into a flat seconds number?
P.S. Time could be sometimes in format MM:SS only.
No need to explode anything:
$str_time = "23:12:95";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = $hours * 3600 + $minutes * 60 + $seconds;
And if you don't want to use regular expressions:
$str_time = "2:50";
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$time_seconds = isset($seconds) ? $hours * 3600 + $minutes * 60 + $seconds : $hours * 60 + $minutes;
I think the easiest method would be to use strtotime() function:
$time = '21:30:10';
$seconds = strtotime("1970-01-01 $time UTC");
echo $seconds;
// same with objects (for php5.3+)
$time = '21:30:10';
$dt = new DateTime("1970-01-01 $time", new DateTimeZone('UTC'));
$seconds = (int)$dt->getTimestamp();
echo $seconds;
demo
Function date_parse() can also be used for parsing date and time:
$time = '21:30:10';
$parsed = date_parse($time);
$seconds = $parsed['hour'] * 3600 + $parsed['minute'] * 60 + $parsed['second'];
demo
If you will parse format MM:SS with strtotime() or date_parse() it will fail (date_parse() is used in strtotime() and DateTime), because when you input format like xx:yy parser assumes it is HH:MM and not MM:SS. I would suggest checking format, and prepend 00: if you only have MM:SS.
demo strtotime()
demo date_parse()
If you have hours more than 24, then you can use next function (it will work for MM:SS and HH:MM:SS format):
function TimeToSec($time) {
$sec = 0;
foreach (array_reverse(explode(':', $time)) as $k => $v) $sec += pow(60, $k) * $v;
return $sec;
}
demo
$time = 00:06:00;
$timeInSeconds = strtotime($time) - strtotime('TODAY');
You can use the strtotime function to return the number of seconds from today 00:00:00.
$seconds= strtotime($time) - strtotime('00:00:00');
In pseudocode:
split it by colon
seconds = 3600 * HH + 60 * MM + SS
Try this:
$time = "21:30:10";
$timeArr = array_reverse(explode(":", $time));
$seconds = 0;
foreach ($timeArr as $key => $value)
{
if ($key > 2) break;
$seconds += pow(60, $key) * $value;
}
echo $seconds;
Simple
function timeToSeconds($time)
{
$timeExploded = explode(':', $time);
if (isset($timeExploded[2])) {
return $timeExploded[0] * 3600 + $timeExploded[1] * 60 + $timeExploded[2];
}
return $timeExploded[0] * 3600 + $timeExploded[1] * 60;
}
function time2sec($time) {
$durations = array_reverse(explode(':', $item->duration));
$second = array_shift($durations);
foreach ($durations as $duration) {
$second += (60 * $duration);
}
return $second;
}
echo time2sec('4:52'); // 292
echo time2sec('2:01:42'); // 7302
On Windows 32 bit PHP version: 7.2.31 i get some error on all versions posted here.
If the time was 00:00:00 or 00:00:00 the zeros 00 were returned and used as "" empty string, and calculation with empty string returns error "A Non WELLNUMERIC blabla.
This Works also with more then 24hours:
function TimeToSec(string $time) {
$timearray = explode(":",$time);
$hours = (int)$timearray[0];
$minutes = (int)$timearray[1];
$seconds = (int)$timearray[2];;
//echo "Hours: " . $hours ."<br>";
//echo "minutes: " . $minutes ."<br>";
//echo "seconds: " . $seconds ."<br>";
$value = ($hours * 3600) + ($minutes * 60) + $seconds;
return $value;
}
echo TimeToSec("25:00:30");
<?php
$time = '21:32:32';
$seconds = 0;
$parts = explode(':', $time);
if (count($parts) > 2) {
$seconds += $parts[0] * 3600;
}
$seconds += $parts[1] * 60;
$seconds += $parts[2];