using mysql DATE_FORMAT

Tuesday 3rd April 2007 03:14 PM

Formatting dates can sometimes be a bit of a pain when selecting very cryptic timestamps from a database. mySQL has some very powerful formatting options however, and users really appreciate having a nice human-readable date presented to them.

For example, if I have a column called submit_date, which is a regular mySQL date/time field, and want to present it in the form of "Friday 21st September 2007" - you would use something like:

SELECT *, DATE_FORMAT(`submit_date`, '%W %D %M %Y') as submit_date_formatted FROM `table`...

The result of the field submit_date_formatted will be a nicely formatted date string. Check the mySQL website for a full list of variables you can use to format your dates.

If you find you use date formatting a lot in your application, it's worth your while to define a variable in a global config somewhere and include this in your queries. This lets you easily change your date formatting in the future, or even allow for user-selectable date formats. e.g

DEFINE('LONG_DATE', '%W %D %M %Y');

... and your query would look something like:

SELECT *, DATE_FORMAT(`submit_date`, '. LONG_DATE .') as submit_date_formatted FROM `table`...

Comments on this article:


I love feedback and comments, be the first!

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).