gointern
gointern

Reputation: 33

Add up time from DateTime in PHP

I'll try to explain my problem. I am beginner with PHP and need help manipulating Date/Time.

So here is my situation.

I get Date/Time values from the database in this format: 07/02/2017 11:00 pm

First I need to calculate a difference between two dates and output duration.

Then add up duration and output total time.

The code is very dirty as I am just researching now. I also came to a problem that DateTime does no carry over points. As far as understand I need to convert days to hours and add them up.

Can anybody more experienced make sense of this?

$total_time = new DateTime('00:00');

$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');

$interval = $start_date->diff($end_date);

$total_days = $interval->days;
$hours      = $interval->h;

if ($total_days !== FALSE) {
    $hours += 24 * $total_days;
}
$minutes    = $interval->i;


$total_time ->add($interval);

echo $hours .'hours ' . $minutes . 'minutes';

echo $total_time->format('h:i'); ?>

Upvotes: 0

Views: 96

Answers (1)

Vitor Furlin
Vitor Furlin

Reputation: 26

You can add a DateInterval to the DateTime.

You can check on http://php.net/manual/en/datetime.add.php

Looking at your code:

$total_hours = 0;
$total_minutes = 0;
//must be initialized outside of the while loop

$start_date = new DateTime('2017-05-01 12:20 PM');
$end_date = new DateTime('2017-05-01 12:30 PM');

$interval = $start_date->diff($end_date);

$hours = $interval->h + 24*$interval->d; /*there is no need to check
if you have total days, since 0 days would still work as expected */

$minutes = $interval->i;

echo 'Duration: '.$hours.' hours '.$minutes.' minutes';

$total_hours += $hours;

if(($total_minutes += $minutes) >= 60) {
    $total_hours += 1;
    $total_minutes -= 60;
}

//after the end of the while loop

echo 'Total time:'.$total_hours.':'.$total_minutes;

Now I don't understand what is the expected output of total time, if you can elaborate on what is not working it would be easier to help

Upvotes: 1

Related Questions