简体   繁体   中英

PhP date time addition

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.

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)));
?>

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM