0

I have 2 variables.

The first -> ("01:10:00")(string); The second -> ("2021-02-23 16:30:00")(string)

I want to add the two to be like "2021-02-23 17:40:00".

How can I accomplish this with PHP?

The answers was very much appreciated, thanks everyone.

3 Answers3

2

You can do it by first exploding the time to add (first variable), then you finally add the exploded information to the date (second variable) using function strtotime:

<?php
$firstVar = "01:10:00";
list($hours, $minutes, $seconds) = explode(":", $firstVar);
$secondVar = "2021-02-23 16:30:00";
echo date('Y-m-d H:i:s',strtotime('+'. $hours .' hour +'. $minutes .' minutes +'. $seconds .' seconds',strtotime($secondVar)));
?>
user3783243
  • 5,368
  • 5
  • 22
  • 41
Johnatha Relvas
  • 336
  • 1
  • 8
1

You can do this:

<?php

$newtimestamp = strtotime('2021-02-23 16:30:00 + 70 minute');
// OR $newtimestamp = strtotime('2021-02-23 16:30:00 + 1 hour + 10 minute');
echo date('Y-m-d H:i:s', $newtimestamp); // Output: 2021-02-23 17:40:00

Anyway, if you need to convert HH:MM:SS to minutes, you can use the following function:

<?php

function minutes($time) {
   $time = explode(':', $time);
   return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}

echo minutes('01:10:00'); // Output: 70

So finally you can do:

<?php

$datetime = '2021-02-23 16:30:00';
$add = minutes('01:10:00');

$newtimestamp = strtotime("$datetime + $add minute");
echo date('Y-m-d H:i:s', $newtimestamp);

function minutes($time) {
   $time = explode(':', $time);
   return ($time[0]*60) + ($time[1]) + ($time[2]/60);
}
AbsoluteBeginner
  • 2,160
  • 3
  • 11
  • 21
1

A solution with DateTime. The time is converted into seconds and added using the modify method.

$timeArr = explode(':',"01:10:00");
$seconds = ($timeArr[0]*60 + $timeArr[1]) *60 + $timeArr[2];
$dateTime = date_create("2021-02-23 16:30:00")->modify($seconds." Seconds");
echo $dateTime->format("Y-m-d H:i:s");

This becomes even easier with the external class dt. This class has an addTime() method.

$dt = dt::create("2021-02-23 16:30:00")->addTime("01:10:00");
echo $dt->format("Y-m-d H:i:s"); //2021-02-23 17:40:00
jspit
  • 7,276
  • 1
  • 9
  • 17