Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP add up two time variables

Tags:

php

mysql

In my PHP application I want to calculate the sum of two time variables. I am looking for something like this example.

$time1 = 15:20:00;
$time2 = 00:30:00;
$time = $time1+$time2;
like image 303
Rakesh Avatar asked Jul 30 '12 11:07

Rakesh


People also ask

How can add hours minutes and seconds in php?

The DateTime::add() function is an inbuilt function in PHP which is used to add an amount of time (days, months, years, hours, minutes and seconds) to the given DateTime object.

How can I get minutes between two dates in php?

$min = $interval ->days * 24 * 60; $min += $interval ->h * 60; $min += $interval ->i; // Printing the Result in Minutes format.

What does NOW () return in php?

MySQL function NOW() returns the current timestamp.


2 Answers

If the answer you expect is 15:50:00 and you want to use strtotime and date functions, you need to subtract the seconds $time1 and $time2 share when you transform them to unix timestamps:

$time1 = '15:20:00';
$time2 = '00:30:00';
$time = strtotime($time1) + strtotime($time2) - strtotime('00:00:00');
$time = date('H:i:s', $time);
like image 82
luissquall Avatar answered Oct 02 '22 14:10

luissquall


The best way to do this is most likely to use strtotime to convert them to timestamps and then do the adding together:

$o = strtotime($time1)+strtotime($time2);

If I remember right strtotime does support this format.

Otherwise you will need to filter it out yourself.

like image 28
Sammaye Avatar answered Oct 02 '22 13:10

Sammaye