Format Date Fields Using MySQL DATE_FORMAT()

By on  

I use MySQL DATE and DATETIME fields almost as much as VARCHAR fields. I use them mostly to track record creation, record updates, and record expiration dates. The default date format in MYSQL is:

2008-09-10 22:50:02

When I pull this information into the page, I want to show the date in human-readable format. That's where MySQL's DATE_FORMAT functionality comes in. DATE_FORMAT allows me to format the date in any manner you'd like.


DATE_FORMAT(NOW(),'%W, %M %e, %Y @ %h:%i %p')
#yields 'Sunday, September 20, 2008 @ 12:45 PM'

MySQL DATE_FORMAT() Letter Representations

Specifier Description
%a Abbreviated weekday name (Sun..Sat)
%b Abbreviated month name (Jan..Dec)
%c Month, numeric (0..12)
%D Day of the month with English suffix (0th, 1st, 2nd, 3rd, …)
%d Day of the month, numeric (00..31)
%e Day of the month, numeric (0..31)
%f Microseconds (000000..999999)
%H Hour (00..23)
%h Hour (01..12)
%I Hour (01..12)
%i Minutes, numeric (00..59)
%j Day of year (001..366)
%k Hour (0..23)
%l Hour (1..12)
%M Month name (January..December)
%m Month, numeric (00..12)
%p AM or PM
%r Time, 12-hour (hh:mm:ss followed by AM or PM)
%S Seconds (00..59)
%s Seconds (00..59)
%T Time, 24-hour (hh:mm:ss)
%U Week (00..53), where Sunday is the first day of the week
%u Week (00..53), where Monday is the first day of the week
%V Week (01..53), where Sunday is the first day of the week; used with %X
%v Week (01..53), where Monday is the first day of the week; used with %x
%W Weekday name (Sunday..Saturday)
%w Day of the week (0=Sunday..6=Saturday)
%X Year for the week where Sunday is the first day of the week, numeric, four digits; used with %V
%x Year for the week, where Monday is the first day of the week, numeric, four digits; used with %v
%Y Year, numeric, four digits
%y Year, numeric (two digits)
%% A literal “%” character
%x x, for any “x” not listed above

Be kind to your users and format the date for them!

Track.js Error Reporting

Recent Features

  • Create Namespaced Classes with MooTools

    MooTools has always gotten a bit of grief for not inherently using and standardizing namespaced-based JavaScript classes like the Dojo Toolkit does.  Many developers create their classes as globals which is generally frowned up.  I mostly disagree with that stance, but each to their own.  In any event,...

  • 7 Essential JavaScript Functions

    I remember the early days of JavaScript where you needed a simple function for just about everything because the browser vendors implemented features differently, and not just edge features, basic features, like addEventListener and attachEvent.  Times have changed but there are still a few functions each developer should...

Incredible Demos


  1. I like to do this kind of transformations on the PHP side, with date(), mktime() and the like. Does anybody know which method is quickest?

  2. @julesj: If you’re pulling from a database, you might as well fit them into the query. If not, continue to use date().

  3. Jeff Hartman

    I typically store all dates in an integer field. That was a habit I got into when most hosts and clients were on MySQL 4.x and there was no datediff function (from what I recall).

    A drawback is that it is impossible to read as an integer when it is stored in the database. However, I find it simple to use with PHP functions. No worries about whether or not the query is formatted properly, etc.

  4. Unix timestamps for the win!

  5. For the record, I’ve referenced this page for the fourth time today at work.

  6. I always use integers to store dates as unixtime. I find that this way it’s easier to do arithmetic on the values before formatting using PHP’s date() function.

  7. Juan Gotti

    This is a great post, Thanks.

    This programming world has been really hard for me because I first needed to lear the language (English) and the apply it to programming, hehe tough task.

    My question is what if I want to have the date in Spanish, what’s the most practical way to crear a custom date function to use it in other languages?

    Thanks in advance!

  8. @Juan: I don’t think MySQL is the best match for that. I would try writing a PHP function to do it. Here’s a good starting point:


  9. Juan Gotti


  10. richard

    I’ve been wondering about what the differences are between timestamp and datetime. are there any big differences between the two?

  11. Bob

    SELECT DATE_FORMAT(time, ‘%Y%c%e’) …..

    Can anyone tell me why this snippet of code errors everytime due to the percentage signs. It does, everytime, yet every example that is ever illustrated uses this convention.

    What gives? If I remove the percentages I get the correct results in other scenarios, just not the correct format.


  12. Hi, I am trying to compare a group of dates with current date and find if its previous so that i could mark it as expired. I tried with strtotime() but it can compare only the current years date and converts the date of other year’s to current years.
    I hope to hear from someone else…Thank you.

  13. http://www.mysqlformatdate.com does all the work for you, all you do is choose the format you want.

  14. @Juan Gotti: hey hello juan this could be prob little late just wanted to give you an option to do this

     $sql = query ("SELECT DATE_FORMAT(date, '%a %d %b %Y %h::%i:%S %p') AS date FROM usuarios WHERE id = '$login'");
     $row = fetch ($sql);
     $eng = array('Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec','Mon','Tue','Wed','Thu','Fri','Sat','Sun');
     $esp = array('Ene','Feb','Mar','Abr','May','Jun','Jul','Ago','Sep','Oct','Nov','Dic','Lunes','Martes','Miercoles','Jueves','Viernes','Sábado','Domingo');
     $row['date'] = str_replace($eng,$esp,$row['date']);
  15. Another gem from the meister – I should have a favorites subfolder called “Dave’s invaluable snippets”

    Cheers again Dave, keep em coming!

  16. u have given good information. but pls tell us code as to how date should be inserted in database, particularly if users input date in dd-mm-yyyy format.

  17. pls give clarification about the difference between date, time and timestamp datatypes in mysql.

  18. aneesh

    thanks for explaining this

  19. byh

    Thanks for the great post. Im using this to fetch data from a website.

  20. Thanks, David. This is a great resource! Say, any idea how one might format AND order by date? I’m getting very unexpected results.

  21. Kyaw Lwin Phyo

    Hi, I’ve tried
    “SELECT ‘Date:’, NOW() into OUTFILE ‘E:\\SUBCON\\EDWHFiles\\Threshold\\time.txt'”
    but I’m getting this value “Date: Wed\ 30\ Nov\ 2011\ 04:59:36\ PM”.
    why is this happening????
    Can anyone explain and correct me??

  22. Kyaw Lwin Phyo

    SELECT ‘Date:’, DATE_FORMAT(NOW(),’%a %d %b %Y %r’) into OUTFILE ‘E:\\SUBCON\\EDWHFiles\\Threshold\\time.txt’

    sorry the query is like this, not as the above.

  23. Aneeq

    I have found a good solution on the site below. Works like charm for me.




  24. wizard

    Awesome Post, Extremely Thankful to you for your invaluable time and effort.

  25. pratik

    thanks it saved time

  26. Shalini

    Wonderful example,i t was same what i was searching for.

    Thanks a lot :)

Wrap your code in <pre class="{language}"></pre> tags, link to a GitHub gist, JSFiddle fiddle, or CodePen pen to embed!

Recently on David Walsh Blog

  • Follow Redirects with cURL

    I love playing around with cURL. There's something about loading websites via command line that makes me feel like some type of smug hacker, just like tweeting from command line does. I recently cURL'd the Google homepage and saw the following: I found it weird that Google...

  • Developers Have WordPress, Amateurs Have Squarespace, Professional Designers Have the NEW Webydo!

    Web design platforms have traditionally come in one of two varieties. There are the solutions like WordPress and Drupal that are incredibly powerful, but an understanding of web development and coding is required to be able to use those platforms effectively. On the other side of the...

  • Chris Coyierâs Favorite CodePen Demos II

    Hey everyone! Before we get started, I just want to say it’s damn hard to pick this few favorites on CodePen. Not because, as a co-founder of CodePen, I feel like a dad picking which kid he likes best (RUDE). But because there is just so...

  • GSAP + SVG For Power Users: Motion Along A Path

    Now that the GreenSock API is picking up steam, there are many tutorials and Getting Started guides out there to provide good introductions to the library, not to mention GreenSock’s own Forum and Documentation. This article isn’t intended for beginners, but rather a...

  • Copy a Directory from Command Line

    Copying a directory for the sake of backup is something I do often, especially when I'm trying to figure out why something isn't working when I use an external library.  I'll copy the directory structure as a backup, mess around with the original source until I find a solution,...