Alex
Alex

Reputation: 1073

Sum of hours and minutes from date or milliseconds

Let`s say we have the time in milliseconds like this, and we want the get the sum of the 3 hours ( 02:00 + 03:00 + 01:30 = 06:30).

1388361603000 equals with Mon Dec 30 2013 02:00:03 GMT+0200
1388365202000 equals with Mon Dec 30 2013 03:00:02 GMT+0200
1388359845000 equals with Mon Dec 30 2013 01:30:45 GMT+0200

If i get the sum of those 3 i get :

4165086650000 equals with Tue Dec 27 2101 02:30:50 GMT+0200

If i get the sum divided by 1000 ( to get the seconds ) the result is this :

4165086650 equals with Wed Feb 18 1970 06:58:06 GMT+0200

Tried like this also and didnt worked :

$time1 = date("H:i", 1388361603000 / 1000);
$time2 = date("H:i", 1388365202000 / 1000);
$time3 = date("H:i", 1388359845000 / 1000);
$total_time = $time1 + $time2 + $time3;

The result was 6, if i remove the : between H and i the result will be 630 ( which still is not good ).

Something that i did and worked was this :

$hours1 = date("H", 1388361603000 / 1000);
$minutes1 = date("i", 1388361603000 / 1000);
$hours2 = date("H", 1388365202000 / 1000);
$minutes2 = date("i", 1388365202000 / 1000);
$hours3 = date("H", 1388359845000 / 1000);
$minutes3 = date("i", 1388359845000 / 1000);

$date = ($hours1 + $hours2 + $hours3) . ":" . ($minutes1 + $minutes2 + $minutes3);
$milliseconds = strtotime($date) * 1000;

echo $date = 6:30

echo $milliseconds = 1388377800000 which equals with Mon Dec 30 2013 06:30:00 GMT+0200

If i get hours bigger then 24 or minutes bigger then 60, i must convert it proper hours and minutes.

Is this the correct way of doing it or there is another simple way ?

Upvotes: 0

Views: 213

Answers (1)

cen
cen

Reputation: 2943

The most simple way I can imagine

echo "Time is: ".date("Y-m-d H:i:s", strtotime("now +3 hours"));

You can also feed strtotime() a UNIX timestamp as second param.

Upvotes: 2

Related Questions