dates and times in php and mysql

Tuesday 21st August 2007 05:13 PM

TAGS: date, time, PHP, mySQL

There are so many different methods of storing dates and times in mySQL fields - and the same goes with generating dates/times from within PHP. To add to the mix, there's also the unix timestamp, which is key to all of this.

The unix timestamp is simply the number of seconds that has passed after Jan. 1st 1970. In this form, it's quite easy to add/subtract time periods, but utterly unreadable by humans.

You can store dates and times in a few ways using mySQL. I tend to prefer to use the date/time column type in mysql, and convert to unixtime on the fly later, as this allows mySQL to still understand that the column is a "date", and not just a meaningless string, this allows you to still retain use of the inbuilt time and date functions.

A few very useful functions come into play here - these are mySQL functions bare in mind, not PHP ones.

FROM_UNIXTIME() will convert a unix timestamp into a mySQL friendly date format. So that you can do things such as:

SELECT * FROM table WHERE article_date=FROM_UNIXTIME(875996580)

You can also select datetime columns AS unixtime in a similar way, using UNIX_TIMESTAMP():

SELECT *, UNIX_TIMESTAMP(article_date) AS article_date FROM table
> article_date: 875996580

In PHP, we have several powerful functions to make use of. One of them you should come to love is strtotime(), you can provide it with almost any string (so that your code is very readable and there are no misunderstandings) simply by supplying it with something like:

strtotime('now + 4 hours'); // returns a unix timestamp 4 hours in the future

If you need to get a bit more dirty, then keep in mind mktime() which can format a date from known time "segments".

As for formatting the date in PHP once you have it in unix timestamp form, simply use date() and provide it the timestamp as the second argument. See the function manual for a full list of formatting, however a basic example would be:

echo date('%d-%m-%Y', strtotime('now + 1 year')); // returns a date in the format 01-01-2008

Comments on this article:


#1 Fallen says:

Friday 14th December 2007 12:45 AM

Wherever possible I am going for the MySQL's TIMESTAMP and then get convertions accordingly, that saves extra time on each opperation and if I have a table with 10mil rows, the difference is really HUGE.
just my 2c


Add Comment:


Make a Comment

*Nb, all comments are moderated to prevent spam or inappropriate content.








netforge logo
netforge provides high quality and friendly website design services to business. We're Australian based and reliable... (find out more).