Date and Time formatting in MySQL

Most developers familiar with SQL Server have employed the easy to use CAST or CONVERT commands in order to properly format a date. Here's a simple example of CONVERT helping us get a value in the format of MM/DD/YYYY.

view plain print about
1SELECT CONVERT(VARCHAR(10), MyDateField, 101) AS MyDateFieldDisplay
2FROM TableName
This is a great command and it's very easy to use - but do you know how to format date and time values in a similar fashion when coding against a MySQL database? You can use the DATE_FORMAT command and here's how...

view plain print about
1SELECT ID,
2 Title,
3 ContentPreview,
4 PublishDateTime,
5 DATE_FORMAT(PublishDateTime, '%m/%d/%Y %h:%i %p') AS PublishDateTimeDisplay,
6FROM Content
This can prove useful when supplying date values for use in a cfgrid via a cfquery returned via a cfc. For more info on building custom date formats with MySQL you can check out MySQL Docs Online.

Related Blog Entries

Comments
Aaron Longnion's Gravatar Thanks for this! I've been meaning to look this up. :)
# Posted By Aaron Longnion | 9/1/09 5:26 AM
Andy Sandefer's Gravatar No problem - glad to be of help.
# Posted By Andy Sandefer | 9/1/09 11:59 AM
ciphone's Gravatar Hello!everyone!iphone is so expensive.so I like <a href=" www.efox-shop.com/index.php/cPath/5_35
" rel="nofollow"> Ciphone </a>. d^_^bIt is very interesting.I want to introduce <a href="http://www.efox-shop.com/"; rel="nofollow"> efox-shop</a> to you.
# Posted By ciphone | 7/30/10 11:21 PM
BlogCFC was created by Raymond Camden. This blog is running version 5.9.5.007. Contact Blog Owner