Dates

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
blazer21
Forum Newbie
Posts: 4
Joined: Wed Jun 22, 2005 3:07 pm

Dates

Post by blazer21 »

How could I take a unix timestamp in php and add 4hours to it?
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Look into strtotime().

Code: Select all

$modified = strototime('+4 hours',$original);
This is better than adding 4 * 60 * 60 seconds, as this takes care of daylight saving time as well (and is just generally cleaner)
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
blazer21
Forum Newbie
Posts: 4
Joined: Wed Jun 22, 2005 3:07 pm

Thanks

Post by blazer21 »

Thanks for the help...
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

blazer21 wrote:PHP v5.0.2

When running the following code date always returns 04:00:00 for the time and not 4 hours past the current time?

Code: Select all

echo $date('m/d/Y h:i:s', strtotime('+4 hours', time()));
In reply to his cross post...

Aside that you should change $date to date it worked fine for me.
Consider trying this

Code: Select all

echo date('m/d/Y h:i:s', strtotime('+4 hours'));
an alternative

Code: Select all

echo date('m/d/Y h:i:s', (time()+14400));
blazer21
Forum Newbie
Posts: 4
Joined: Wed Jun 22, 2005 3:07 pm

Post by blazer21 »

Funny I can't seem to get strtotime('+4 hours') to work correctly even using your posted code. So, I'm going to use the following.

Code: Select all

echo date('h:i:s', (time()+14400));
User avatar
John Cartwright
Site Admin
Posts: 11470
Joined: Tue Dec 23, 2003 2:10 am
Location: Toronto
Contact:

Post by John Cartwright »

Try this custom function found at http://ca3.php.net/strtotime who have reported strtotime having some problems with php5

Code: Select all

function strtotimefix($strtotime)
{
   return time() + (strtotime($strtotime) - strtotime('now'));
}
Last edited by John Cartwright on Wed Jun 22, 2005 4:57 pm, edited 1 time in total.
User avatar
pickle
Briney Mod
Posts: 6445
Joined: Mon Jan 19, 2004 6:11 pm
Location: 53.01N x 112.48W
Contact:

Post by pickle »

Ya, if you're having problems, use ~Jcart's suggestion rather than adding seconds - that always causes problems!
Real programmers don't comment their code. If it was hard to write, it should be hard to understand.
Post Reply