Time Travel with PHP

What do you do if your main audience for your website is mostly in one time zone, and your web server is in another and you want to use the date function in PHP? This article will teach you how to compensate for the time difference so the right time and date will display for your intended audience.

I have built many web applications over the years for clients in the Pacific Standard Time zone. The problem is that my server is located in EST or Eastern Standard Time. So when I make use of the date() in my PHP programs, there is always a time difference involved. For ordering systems, this can be confusing because the time stamp may be for a zone that neither the buyer or the seller is in. In other cases it will show Tuesday as the current day even though it is still 9pm on a Monday.

So how do we easily correct for this? Also what about adding or subtracting days from the date? I will show you a little programming trick that took me a long time to find the answer to. Here is the function that will do the trick.

$newdate = date("Y-m-d H:i:s",strtotime(date('Y-m-j H:i:s')) - (60 * 24 * 60 * 60));

This will subtract 60 days from the current date and output it in normal date time format. So how does it do this so I know how to make use of it more effectively? The key part is the strtotime() function. It will take the current date time and convert it into seconds from the time of Christ. That would be AD 0 for you non-Christians. You say, that's a lot of seconds. No kidding! So removing a few is not going to hurt. Feel free to output the number to the screen. It is only 1,088,210,322. At least it was a couple of seconds ago.

So we are removing 5,184,000 seconds from 1,088,210,322. That comes from knowing that there are 60 days in to month or about that. 24 hours in every day, 60 minutes in every hour, and 60 seconds in every minute. So we just multiply them. Time to use some of those math stills you learned in college. Here is how to do the math. Step 1. Remove calculator from shelf, drawer, or bag. Step 2. Turn it on. Step 3. Punch in 60 * 24 * 60 * 60 and you will get 5,184,000. If you want 3 hours that would be 3*60*60.

If you want to add 3 hours, then just change the minus sign before the (3 * 60 * 60) to a plus like date("Y-m-d H:i:s",strtotime(date('Y-m-j H:i:s')) + (3 * 60 * 60));.

Easy enough? Great, have fun with it. Who says that time travel is not possible. With PHP you can.

Written June, 2004 © Truecast Design Studio. Author: Dan Baldwin.