Redzwan Latif
Redzwan Latif

Reputation: 886

Add hours to datetime in PHP

I got a variable named $transactiontime. I want to add 6 hours to that variable. But I need to exclude the time between 12.00AM and 6.00AM.

For example, I made a transaction at 1/1/2016 11.00PM. After adding 6 hours, the output should be 2/1/2016 11.00AM.

How do I do this? Thank you

Upvotes: 4

Views: 2016

Answers (1)

Kevin Kopf
Kevin Kopf

Reputation: 14230

DateTime is an awesome feature in PHP

$string = '1/1/2016 11.00PM';

$date = new DateTime($string);
$interval = new DateInterval('PT6H');
$date->add($interval);

// Now add another 6 hours while we are between 12:00 AM and 6:00 AM
while($date->format('G') >= 0 && $date->format('G') <= 6)
{
    $date->add($interval);    
}

echo $date->format('H:i:s M-j-Y');

This outputs the desired

11:00:00 Jan-2-2016

Update

After our extensive discussion in chat about the logic of this particular piece of code, we came to the conclusion, that any transaction done between midnight and 6:00 AM should add 6 hours starting from 6:00 AM (so, basically, set it to midday).

And every other transaction adds 6 hours normally. But if after adding those 6 hours the time interval falls between midnight and 6:00 AM, only the respective amount of time between the initial and midnight and the rest should be added to 6:00 AM, which is, basically is adding just 12 hours to the initial value.

So here's the modified code:

$date = new DateTime($string);
$interval = new DateInterval('PT6H');

if($date->format('G') >= 0 && $date->format('G') <= 6)
{
    $date->setTime(12,0,0);
}
else
{
    $date->add($interval);
    if($date->format('G') >= 0 && $date->format('G') <= 6)
    {
        $date->add($interval);
    }
}

echo $date->format('H:i:s M-j-Y');

Example #1

// input
$string = '1/1/2016 3.00AM';

//output
12:00:00 Jan-1-2016 // this is midday

Example #2

// input
$string = '1/1/2016 11.00AM';

//output
17:00:00 Jan-1-2016 // this is 5:00 PM

Example #3

// input
$string = '1/1/2016 11.00PM';

//output
11:00:00 Jan-2-2016 // this is 11:00 AM

Upvotes: 4

Related Questions