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)
Related
Here is my code:
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
echo $result;
The output of the above code is - 07:38:05
i want it to display like this - 31:38:05. How can i achieve this?
Convert both times to seconds, add them, and then calculate the hours, minutes, and seconds yourself.
$time = "20:58:05";
$time2 = "10:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
The solution of Barmar works when adding hours that are below 24:00:00, but when you add 2 variable with each variable exceeds 24:00:00 it gives a wrong output. For example:
$time = "20:58:05";
$time2 = "30:40:00";
$secs = strtotime($time)-strtotime("00:00:00");
$secs2 = strtotime($time2)-strtotime("00:00:00");
$total = $secs + $secs2;
$hours = floor($total/3600);
$mins = floor(($total % 3600) / 60);
$secs = $total % 60;
echo sprintf("%d:%02d:%02d", $hours, $mins, $secs);
output of the above code: -431348:-2:-55
Here is a code that works even if the data of the variables exceeds 24:00:00:
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
i found this code here
Is there any way to sum two times with milliseconds like this:
00:01:02.73
00:03:03.01
to one?
the result should be like this:
00:04:05.74
format is simple "hours:minutes:seconds.milliseconds"
If yes, how?
well I wrote few functions which is helping me to do that
$time1 = "00:15:45.89";
$time2 = "00:18:30.22";
$milli1 = timeToMilliseconds($time1);
$milli2 = timeToMilliseconds($time2);
$new = $milli1 + $milli2;
$time = formatMilliseconds($new);
echo $time;
function timeToMilliseconds($time){
$time_start = substr($time, -11, -3);
$time_end = substr($time, -3);
$time_arr = explode(':', $time_start);
$seconds = 0;
foreach($time_arr as $key => $val){
if($key == 0){
$seconds += $val * 60 * 60;
}elseif($key == 1){
$seconds += $val * 60;
}elseif($key == 2){
$seconds += $val;
}
}
$seconds = $seconds.$time_end;
$milliseconds = $seconds * 1000;
return $milliseconds;
}
function formatMilliseconds($milliseconds) {
$seconds = floor($milliseconds / 1000);
$minutes = floor($seconds / 60);
$hours = floor($minutes / 60);
$milliseconds = $milliseconds % 1000;
$seconds = $seconds % 60;
$minutes = $minutes % 60;
$format = '%u:%02u:%02u.%03u';
$time = sprintf($format, $hours, $minutes, $seconds, $milliseconds);
return rtrim($time, '0');
}
Has a problem with your solution #Scorpioniz, when the time is "1:34:55.831" for example, the return from formatMilliseconds is "1582:10:31.704".
I made some changes in the timeToMilliseconds function and I think that is more consistent:
function timeToMilliseconds($time){
$dateTime = new DateTime($time);
$seconds = 0;
$seconds += $dateTime->format('H') * 3600;
$seconds += $dateTime->format('i') * 60;
$seconds += $dateTime->format('s');
$seconds = floatval($seconds . '.' . $dateTime->format('u'));
return $seconds * 1000;
}
Or if your version of PHP is minor than 5.2.2 then you can do:
function timeToMilliseconds($time){
sscanf($time, "%d:%d:%d.%d", $hours, $minutes, $seconds, $microseconds);
$seconds += $hours * 3600;
$seconds += $minutes * 60;
$seconds = floatval($seconds . '.' . $microseconds);
return $seconds * 1000;
}
I hope someone enjoy.
(Sorry for my English if I said something strange :P)
I've found this, it has less code than yours and it does the job. I've added function for milliseconds.
I'm wondering if php has something built-in for this.
/**
* #author Masino Sinaga, http://www.openscriptsolution.com
* #copyright October 13, 2009
*/
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
$Imiliseconds = 0.0;
foreach ($times as $time){
list($rest, $miliseconds) = explode('.', $time);
$Imiliseconds += '0.'.$miliseconds;
list($hour, $minute, $second) = explode(':', $rest);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$seconds += floor($Imiliseconds);
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
$miliseconds = $Imiliseconds-floor($Imiliseconds);
// return "{$hours}:{$minutes}:{$seconds}:{$miliseconds}";
return sprintf('%02d:%02d:%02d:%02d', $hours, $minutes, $seconds, $miliseconds); // Thanks to Patrick
}
echo sum_the_time($time, $time2); // this will give you a result: 19:12:25
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 );
i have two time values as give below
$time = 06:58:00;
$time2 = 00:40:00;
I am doing this for calculating the appointments and available time for a particular user
so i tried in this way
$max_date=abs(strtotime($time) + strtotime($time2));
but it is returning $max_date =2673452280
any suggestions pls
this code sample would take hour in $time and add the hour in $time2 to it
for example: time=06:58:00, time2=00:40:00, result = 07:38:00
$time = "06:58:00";
$time2 = "00:40:00";
$secs = strtotime($time2)-strtotime("00:00:00");
$result = date("H:i:s",strtotime($time)+$secs);
Use this function...
function sum_the_time($time1, $time2) {
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
strtotime function takes full-date as an argument and valid format are as following:
http://www.php.net/manual/en/datetime.formats.php
You can see that in online PHP manual for the function at http://php.net/manual/en/function.strtotime.php
If you're build those time strings from a database before, you'd probably want to rebuild them to something like this:
$time = "00:06:58";
$time2 = "40 minutes";
$timestamp = strtotime($time." +".$time2);
$endTime = date("d.m.Y H:i:s", $timestamp);
Easiest way to add two times using php is :
1) Convert time from H:i:s (e.g. 08:15:40) format to seconds.
2) do the same for second time value ref:step 1
3) add converted values and store it php variable
4) Now convert total (which is in seconds) to H:i:s
and it works for me.
PHP Script:
$str_time ="08:04:40";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_old_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$str_time ="02:10:22";
$str_time = preg_replace("/^([\d]{1,2})\:([\d]{2})$/", "00:$1:$2", $str_time);
sscanf($str_time, "%d:%d:%d", $hours, $minutes, $seconds);
$hrs_toadd_seconds = $hours * 3600 + $minutes * 60 + $seconds;
$hrs_old_int1 = $hrs_old_seconds + $hrs_toadd_seconds;
echo $Total=gmdate("H:i:s", $hrs_old_int1);
Result= :10:15:02
Anudeep's solution was great for my use case, but I needed to be able to add negative times as well. Here's a slightly edited version of his code to take and return negative time strings ("-01:01:01" for example):
public static function sum_the_times($time1, $time2)
{
$times = array($time1, $time2);
$seconds = 0;
$negative = false;
foreach ($times as $time) {
list($hour,$minute,$second) = explode(':', $time);
if(substr($hour,0,1) == '-'){
$seconds -= substr($hour,1)*3600;
$seconds -= $minute*60;
$seconds -= $second;
} else {
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
}
if (substr($seconds, 0, 1) == '-') {
$negative = true;
$seconds = ($seconds * -1);
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if ($seconds < 9) {
$seconds = "0".$seconds;
}
if ($minutes < 9) {
$minutes = "0".$minutes;
}
if ($hours < 9) {
$hours = "0".$hours;
}
return ($negative ? "-" : "")."{$hours}:{$minutes}:{$seconds}";
}
You can try this
$time = "04:00:00";
$time2 = "03:30:00";
$result = date("H:i:s",strtotime($time)+strtotime($time2));
echo $result;
It gives output 07:30:00 but it does not work sometime in different version of operating system. If you want to get sum of time then you can use this code
<?php
function CalculateTime($time1, $time2) {
$time1 = date('H:i:s',strtotime($time1));
$time2 = date('H:i:s',strtotime($time2));
$times = array($time1, $time2);
$seconds = 0;
foreach ($times as $time)
{
list($hour,$minute,$second) = explode(':', $time);
$seconds += $hour*3600;
$seconds += $minute*60;
$seconds += $second;
}
$hours = floor($seconds/3600);
$seconds -= $hours*3600;
$minutes = floor($seconds/60);
$seconds -= $minutes*60;
if($seconds < 9)
{
$seconds = "0".$seconds;
}
if($minutes < 9)
{
$minutes = "0".$minutes;
}
if($hours < 9)
{
$hours = "0".$hours;
}
return "{$hours}:{$minutes}:{$seconds}";
}
$time1= '23:32:05';
$time2 = '01:29';
echo CalculateTime($time1,$time2);
?>
In the second code, you can send time in hour:minutes or hours:minutes:seconds. This code accept both format because it convert time automatically
Here's a version that will cater for over 24 hours and doesn't use strtotime:
$time0 = "24:01:02";
$time1 = "01:02:03";
$matches0 = explode(':',$time0); // split up the string
$matches1 = explode(':',$time1);
$sec0 = $matches0[0]*60*60+$matches0[1]*60+$matches0[2];
$sec1 = $sec0+ $matches1[0]*3600+$matches1[1]*60+$matches1[2]; // get total seconds
$h = intval(($sec1)/3600);
$m = intval(($sec1-$h*3600)/60);
$s = $sec1-$h*3600-$m*60;
echo $str = str_pad($h, 2, '0', STR_PAD_LEFT).':'.str_pad($m, 2, '0', STR_PAD_LEFT).':'.str_pad($s, 2, '0', STR_PAD_LEFT);
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];