mhopkins321
mhopkins321

Reputation: 3073

Adding two times together in php

I am looking to add two times together that come from a sql query. Below is my code.

$taskID = $row['taskID'];
$startTimeRaw = $row['startTime'];
$endTimeRaw = $row['endTime'];
$everyMinutesRaw = $row['everyMinutes'];
$startTime = $startTimeRaw->format('H:i:s');
$endTime = $endTimeRaw->format('H:i:s');
$everyMinutes = $everyMinutesRaw->format('H:i:s');

#$latestRunTime = $startTime;
$latestRunTimeRaw = $startTime + $everyMinutes;


echo $startTime."<BR>";
echo $everyMinutes."<BR>";
echo $latestRunTime."<BR>";

This code returns the following

06:05:00
00:15:00
6

The third line of the return should be 06:20:00, how can I make this change. I've played with strtotime and ->format() but none of it seems to get the proper answer. Thoughts?

With the data contained in the other answer I have this

$latestRunTime = strtotime($startTime) + strtotime($everyMinutes);

And it outputs

2733243600

If I format that, I get the following

Fatal error: Call to a member function format() on a non-object in 

Upvotes: 0

Views: 4569

Answers (2)

Anudeep Sharma
Anudeep Sharma

Reputation: 147

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}";
}

Use this function in every where just call the function when you need..Thanks

Upvotes: 1

Wrikken
Wrikken

Reputation: 70460

This seems to be what you're after:

<?php
$period = new DatePeriod(
        new DateTime('06:05:00'),
        DateInterval::createFromDateString('15 minutes'),
        new DateTime('07:00:00'));
foreach($period as $interval){
        echo $interval->format('c').PHP_EOL;
}

Result:

2013-04-22T06:05:00+02:00
2013-04-22T06:20:00+02:00
2013-04-22T06:35:00+02:00
2013-04-22T06:50:00+02:00

You could also use new DateInterval('PT15M'), or more formally from a time:

new DateInterval('PT'.$everyMinutesRaw->format('H\Hi\Ms\S'));

If you're not interested in all the intervals but just want the first one as per your example:

 $startTimeRaw->add(new DateInterval('PT'.$everyMinutesRaw->format('H\Hi\Ms\S')));
 echo $startTimeRaw->format('H:i:s');

Upvotes: 1

Related Questions