PHP date()-style formatting for JavaScript

December 1, 2015 · Posted in Bits & Bobs 

If you’ve ever had to work with the JavaScript Date object, you might have come accross the same problem that I had recently: formatting dates and times in a nice way is difficult to do. The options you get for producing date and time strings are limited, at best: aside from a few predefined, not very pretty formats, no functions are provided at all for this type of thing.

At the other end of the spectrum, PHP provides a function called date(), which takes a format string somewhat reminiscent of printf-type functions, along with a Unix timestamp, and provides a wide variety of options for formatting dates and times to your heart’s content. So I figured, why not take that concept to JavaScript?

The script attached to this post does exactly that. It adds a function to the Date object, called format(), which takes a format string in the exact same way that PHP’s date() does, and returns the date and time formatted according to your wishes. It comes with only a few limitations:

  • The z, W, o, e, I, and T formatting options are not implemented, and an exception is thrown if you try to use them (however, by escaping these letters you can still get them to appear in the output string as literals). All of these formatting options relate either to timezones (for which no data is available beyond the GMT/UTC offset), or ISO-8601 week numbers (which are rarely used anyway), so this should not prove to be too much of a limitation.
  • When using the U formatting option, which is supposed to display the microseconds, the last three digits will always be 0 because JavaScript has no way of retrieving that information (but the milliseconds are shown).
  • The predefined date formats that PHP has (such as DATE_RSS, DATE_ISO8601, and so on) are not currently implemented (but can easily be replicated by putting together the appropriate formatting options yourself).

Having said that, I am happy to share with you this script, in two tasty versions. Both are free to use under the GNU General Public License version 2.

  • Compressed version (2.76 kB)
    Recommended for most cases. It’s not very readable, but doesn’t have as much of an impact on page load times.
  • Source code (8.50 kB)
    Useful if you want to tinker with the code yourself.


Leave a Reply

A Soul Waking