user3328761
user3328761

Reputation: 11

Convert Date to Hours only using PHP

I would to add a certain amount of hours to a date time using PHP. I am interested to show the result only using hour format.

For example, I add 8 hours to a date time as follow:

$result= date("H:i", strtotime('18:00') + 8*3600);

But I got as result value 01:00, but I would get 26 as result..

Can you help me please, I could not find the solution :(

Thank you all

Upvotes: 0

Views: 1345

Answers (2)

Marc B
Marc B

Reputation: 360702

Basic PHP dates math. strtotime() returns a unix timestamp, which is number of seconds since the epoch, midnight January 1,1970.

date() takes those timestamps and formats them into whatever representation you want. But 'H' is NOT "hours since time zero". it's "hours of the day". If you have a timestamp that represents Jul 8/2014 12 noon, then H is going to be 12, because it's noon. It's not going to be 50 bajillion hours since Jan 1/1970.

e.g.

Jul 8/2014 11pm  + 3 hours = Jul 9/2014 2am. 
date('H' of Jul 9/2014)  = 2, not "14"

Upvotes: 0

Gergo Erdosi
Gergo Erdosi

Reputation: 42043

It's easier with DateTime:

$date = new DateTime('18:00:00');
$date->modify('+8 hours');
echo $date->format('H:i');

Edit: Maybe I don't understand the question then. If you want to get 26, then you can use something like:

$date = new DateTime('18:00:00');
echo $date->format('H') + 8;

Upvotes: 2

Related Questions