Handling dates and times in PHP & MySQL(Page 1 out of 3)
This article will show you how to use dates and times in PHP & MySQL, by taking a look at the problems that arise when handling dates and times, and how to solve them
Whenever you create a PHP script, there's a big chance it'll involve handling dates and times, when for example you need to create a content management system or an event tracker. Handling dates and times in your scripts doesn't sound so hard, after all, it's just a few numbers to track, but in reality this is actually much harder than you think. In fact, using dates and times can be one of the most challenging tasks to do, especially if you want to do it properly.
That's why in this article I'm going to take you through the necessary steps to properly handle dates and times. First we'll have a look at the problem, and after that we'll go through the steps necessary to solve it.
The problem: handling dates and times
It seems really easy, to use dates and time, and most of us tend to take the easy road, and simply store a timestamp in the database. It's not uncommon to see something like this:
// Get item variables
// Generate timestamp
$item['timestamp'] = time();
// Insert item
This is probably the way most of us do it, and in fact, that's how I usually do it as well, because there's no hassle at all.
But there are several problems with this method. The biggest problem is that the timezone of this date isn't taken in account. If you don't know what a timezone is, it's a zone where a certain time is set, and there are different timezones all over the world. For example, I live in the GMT+1 timezone, which means it could be 10 PM here, and 1 AM in the US.
Getting back to the problem, the timestamp stored in the database is based on the timezone of the server, but what if we move to a different server with a different timezone? Or what if we want to display the date in the visitor's own timezone? That would be impossible, since we don't know the original timezone.
To solve the problem we need to store the timezone along with the timestamp. To do that, we must use the base timezone called GMT as the reference, and account for the number of hours our timezone is different from the GMT timezone. The easiest way to do that is to get the offset with the date() function and using the 'Z' argument as format, see the example below:
// Get GMT timestamp
$gm_time = time() - date('Z', time());