JavaScript Date Format

Update: The documentation below has been updated for the new Date Format 1.2. Get it now!

Although JavaScript provides a bunch of methods for getting and setting parts of a date object, it lacks a simple way to format dates and times according to a user-specified mask. There are a few scripts out there which provide this functionality, but I've never seen one that worked well for me… Most are needlessly bulky or slow, tie in unrelated functionality, use complicated mask syntaxes that more or less require you to read the documentation every time you want to use them, or don't account for special cases like escaping mask characters within the generated string.

When choosing which special mask characters to use for my JavaScript date formatter, I looked at PHP's date function and ColdFusion's discrete dateFormat and timeFormat functions. PHP uses a crazy mix of letters (to me at least, since I'm not a PHP programmer) to represent various date entities, and while I'll probably never memorize the full list, it does offer the advantages that you can apply both date and time formatting with one function, and that none of the special characters overlap (unlike ColdFusion where m and mm mean different things depending on whether you're dealing with dates or times). On the other hand, ColdFusion uses very easy to remember special characters for masks.

With my date formatter, I've tried to take the best features from both, and add some sugar of my own. It did end up a lot like the ColdFusion implementation though, since I've primarily used CF's mask syntax.

Before getting into further details, here are some examples of how this script can be used:

var now = new Date();

now.format("m/dd/yy");
// Returns, e.g., 6/09/07

// Can also be used as a standalone function
dateFormat(now, "dddd, mmmm dS, yyyy, h:MM:ss TT");
// Saturday, June 9th, 2007, 5:46:21 PM

// You can use one of several named masks
now.format("isoDateTime");
// 2007-06-09T17:46:21

// ...Or add your own
dateFormat.masks.hammerTime = 'HH:MM! "Can\'t touch this!"';
now.format("hammerTime");
// 17:46! Can't touch this!

// When using the standalone dateFormat function,
// you can also provide the date as a string
dateFormat("Jun 9 2007", "fullDate");
// Saturday, June 9, 2007

// Note that if you don't include the mask argument,
// dateFormat.masks.default is used
now.format();
// Sat Jun 09 2007 17:46:21

// And if you don't include the date argument,
// the current date and time is used
dateFormat();
// Sat Jun 09 2007 17:46:22

// You can also skip the date argument (as long as your mask doesn't
// contain any numbers), in which case the current date/time is used
dateFormat("longTime");
// 5:46:22 PM EST

// And finally, you can convert local time to UTC time. Either pass in
// true as an additional argument (no argument skipping allowed in this case):
dateFormat(now, "longTime", true);
now.format("longTime", true);
// Both lines return, e.g., 10:46:21 PM UTC

// ...Or add the prefix "UTC:" to your mask.
now.format("UTC:h:MM:ss TT Z");
// 10:46:21 PM UTC

Following are the special characters supported. Any differences in meaning from ColdFusion's dateFormat and timeFormat functions are noted.

Mask Description
d Day of the month as digits; no leading zero for single-digit days.
dd Day of the month as digits; leading zero for single-digit days.
ddd Day of the week as a three-letter abbreviation.
dddd Day of the week as its full name.
m Month as digits; no leading zero for single-digit months.
mm Month as digits; leading zero for single-digit months.
mmm Month as a three-letter abbreviation.
mmmm Month as its full name.
yy Year as last two digits; leading zero for years less than 10.
yyyy Year represented by four digits.
h Hours; no leading zero for single-digit hours (12-hour clock).
hh Hours; leading zero for single-digit hours (12-hour clock).
H Hours; no leading zero for single-digit hours (24-hour clock).
HH Hours; leading zero for single-digit hours (24-hour clock).
M Minutes; no leading zero for single-digit minutes.
Uppercase M unlike CF timeFormat's m to avoid conflict with months.
MM Minutes; leading zero for single-digit minutes.
Uppercase MM unlike CF timeFormat's mm to avoid conflict with months.
s Seconds; no leading zero for single-digit seconds.
ss Seconds; leading zero for single-digit seconds.
l or L Milliseconds. l gives 3 digits. L gives 2 digits.
t Lowercase, single-character time marker string: a or p.
No equivalent in CF.
tt Lowercase, two-character time marker string: am or pm.
No equivalent in CF.
T Uppercase, single-character time marker string: A or P.
Uppercase T unlike CF's t to allow for user-specified casing.
TT Uppercase, two-character time marker string: AM or PM.
Uppercase TT unlike CF's tt to allow for user-specified casing.
Z US timezone abbreviation, e.g. EST or MDT. With non-US timezones or in the Opera browser, the GMT/UTC offset is returned, e.g. GMT-0500
No equivalent in CF.
o GMT/UTC timezone offset, e.g. -0500 or +0230.
No equivalent in CF.
S The date's ordinal suffix (st, nd, rd, or th). Works well with d.
No equivalent in CF.
'…' or "…" Literal character sequence. Surrounding quotes are removed.
No equivalent in CF.
UTC: Must be the first four characters of the mask. Converts the date from local time to UTC/GMT/Zulu time before applying the mask. The "UTC:" prefix is removed.
No equivalent in CF.

And here are the named masks provided by default (you can easily change these or add your own):

Name Mask Example
default ddd mmm dd yyyy HH:MM:ss Sat Jun 09 2007 17:46:21
shortDate m/d/yy 6/9/07
mediumDate mmm d, yyyy Jun 9, 2007
longDate mmmm d, yyyy June 9, 2007
fullDate dddd, mmmm d, yyyy Saturday, June 9, 2007
shortTime h:MM TT 5:46 PM
mediumTime h:MM:ss TT 5:46:21 PM
longTime h:MM:ss TT Z 5:46:21 PM EST
isoDate yyyy-mm-dd 2007-06-09
isoTime HH:MM:ss 17:46:21
isoDateTime yyyy-mm-dd'T'HH:MM:ss 2007-06-09T17:46:21
isoUtcDateTime UTC:yyyy-mm-dd'T'HH:MM:ss'Z' 2007-06-09T22:46:21Z

A couple issues:

  • In the unlikely event that there is ambiguity in the meaning of your mask (e.g., m followed by mm, with no separating characters), put a pair of empty quotes between your metasequences. The quotes will be removed automatically.
  • If you need to include literal quotes in your mask, the following rules apply:
    • Unpaired quotes do not need special handling.
    • To include literal quotes inside masks which contain any other quote marks of the same type, you need to enclose them with the alternative quote type (i.e., double quotes for single quotes, and vice versa). E.g., date.format('h "o\'clock, y\'all!"') returns "6 o'clock, y'all". This can get a little hairy, perhaps, but I doubt people will really run into it that often. The previous example can also be written as date.format("h") + "o'clock, y'all!".

Here's the code:

/*
 * Date Format 1.2.3
 * (c) 2007-2009 Steven Levithan <stevenlevithan.com>
 * MIT license
 *
 * Includes enhancements by Scott Trenda <scott.trenda.net>
 * and Kris Kowal <cixar.com/~kris.kowal/>
 *
 * Accepts a date, a mask, or a date and a mask.
 * Returns a formatted version of the given date.
 * The date defaults to the current date/time.
 * The mask defaults to dateFormat.masks.default.
 */

var dateFormat = function () {
	var	token = /d{1,4}|m{1,4}|yy(?:yy)?|([HhMsTt])\1?|[LloSZ]|"[^"]*"|'[^']*'/g,
		timezone = /\b(?:[PMCEA][SDP]T|(?:Pacific|Mountain|Central|Eastern|Atlantic) (?:Standard|Daylight|Prevailing) Time|(?:GMT|UTC)(?:[-+]\d{4})?)\b/g,
		timezoneClip = /[^-+\dA-Z]/g,
		pad = function (val, len) {
			val = String(val);
			len = len || 2;
			while (val.length < len) val = "0" + val;
			return val;
		};

	// Regexes and supporting functions are cached through closure
	return function (date, mask, utc) {
		var dF = dateFormat;

		// You can't provide utc if you skip other args (use the "UTC:" mask prefix)
		if (arguments.length == 1 && Object.prototype.toString.call(date) == "[object String]" && !/\d/.test(date)) {
			mask = date;
			date = undefined;
		}

		// Passing date through Date applies Date.parse, if necessary
		date = date ? new Date(date) : new Date;
		if (isNaN(date)) throw SyntaxError("invalid date");

		mask = String(dF.masks[mask] || mask || dF.masks["default"]);

		// Allow setting the utc argument via the mask
		if (mask.slice(0, 4) == "UTC:") {
			mask = mask.slice(4);
			utc = true;
		}

		var	_ = utc ? "getUTC" : "get",
			d = date[_ + "Date"](),
			D = date[_ + "Day"](),
			m = date[_ + "Month"](),
			y = date[_ + "FullYear"](),
			H = date[_ + "Hours"](),
			M = date[_ + "Minutes"](),
			s = date[_ + "Seconds"](),
			L = date[_ + "Milliseconds"](),
			o = utc ? 0 : date.getTimezoneOffset(),
			flags = {
				d:    d,
				dd:   pad(d),
				ddd:  dF.i18n.dayNames[D],
				dddd: dF.i18n.dayNames[D + 7],
				m:    m + 1,
				mm:   pad(m + 1),
				mmm:  dF.i18n.monthNames[m],
				mmmm: dF.i18n.monthNames[m + 12],
				yy:   String(y).slice(2),
				yyyy: y,
				h:    H % 12 || 12,
				hh:   pad(H % 12 || 12),
				H:    H,
				HH:   pad(H),
				M:    M,
				MM:   pad(M),
				s:    s,
				ss:   pad(s),
				l:    pad(L, 3),
				L:    pad(L > 99 ? Math.round(L / 10) : L),
				t:    H < 12 ? "a"  : "p",
				tt:   H < 12 ? "am" : "pm",
				T:    H < 12 ? "A"  : "P",
				TT:   H < 12 ? "AM" : "PM",
				Z:    utc ? "UTC" : (String(date).match(timezone) || [""]).pop().replace(timezoneClip, ""),
				o:    (o > 0 ? "-" : "+") + pad(Math.floor(Math.abs(o) / 60) * 100 + Math.abs(o) % 60, 4),
				S:    ["th", "st", "nd", "rd"][d % 10 > 3 ? 0 : (d % 100 - d % 10 != 10) * d % 10]
			};

		return mask.replace(token, function ($0) {
			return $0 in flags ? flags[$0] : $0.slice(1, $0.length - 1);
		});
	};
}();

// Some common format strings
dateFormat.masks = {
	"default":      "ddd mmm dd yyyy HH:MM:ss",
	shortDate:      "m/d/yy",
	mediumDate:     "mmm d, yyyy",
	longDate:       "mmmm d, yyyy",
	fullDate:       "dddd, mmmm d, yyyy",
	shortTime:      "h:MM TT",
	mediumTime:     "h:MM:ss TT",
	longTime:       "h:MM:ss TT Z",
	isoDate:        "yyyy-mm-dd",
	isoTime:        "HH:MM:ss",
	isoDateTime:    "yyyy-mm-dd'T'HH:MM:ss",
	isoUtcDateTime: "UTC:yyyy-mm-dd'T'HH:MM:ss'Z'"
};

// Internationalization strings
dateFormat.i18n = {
	dayNames: [
		"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
		"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
	],
	monthNames: [
		"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
		"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"
	]
};

// For convenience...
Date.prototype.format = function (mask, utc) {
	return dateFormat(this, mask, utc);
};

Download it here (1.2 KB when minified and gzipped).

Note that the day and month names can be changed (for internationalization or other purposes) by updating the dateFormat.i18n object.

If you have any suggestions or find any issues, lemme know.


Want to learn about aphantasisa and hyperphantasia, the Shen Yun cult, or unmasking cult leader Karen Zerby? Check out my new blog at Life After Tech.

377 thoughts on “JavaScript Date Format”

  1. Thank you so much, that helped me so much; but, for me, “M” worked for months while “m” worked for minutes, also, the “S” suffix didn’t work.

  2. This is throwing an error:
    var time = now.format(“longTime”, true);

    Also, can’t get any UTC stuff to work.

  3. var time = now.format(“UTC:HH”);

    this returns:
    UTC:15

    so it looks like the parsing of that keyword isn’t working..

  4. @burl, I can’t reproduce the problem. (new Date).format("longTime", true) and (new Date).format("UTC:HH") work correctly for me. I just ran the two lines in Firefox and IE after loading Date Format 1.2.3, and got "12:37:20 PM UTC" and "12" in both browsers. What error are you getting? Has your now variable been defined properly?

  5. Thanks for the reply, I did get it to work. FYI I was using a window onload event to have a running clock. I needed to load the JavaScript library at the bottom (best practice anyway) before the closing

    Here’s the code for the clock:

    window.onload = WindowLoad;
    function WindowLoad(event) {
    var now = new Date();
    var day = now.format(“dddd, yyyy-mm-dd”);
    var time = now.format(“UTC:HH:MM:ss”);
    if (document.getElementById) {
    document.getElementById(‘datestamp’).innerHTML = day + ‘ ‘ + time;
    }
    else if (document.layers){
    document.layers.theTime.document.write(day + ‘ ‘ + time);
    document.layers.theTime.document.close();
    }
    setTimeout(“WindowLoad()”, 1000);
    }

    Thanks for this useful library.

  6. Oops – IE7 is not behaving. [Using above code block]

    IE7 displays: Tuessday, 2009-32-07 UTC:09:07:24

    FF 3.5 displays: Tuesday, 2009-07-07 16:32:59

    Maybe the “MM” for minutes is not working for the UTC time and breaking that and also looks like the “mm” is not being picked up either for the month.

  7. @burl, no. The test I mentioned earlier works fine in IE6+ (and probably 5.5 as well). I don’t know what you’re doing in your code, if you’re running a conflicting library, or what may be different in your browser. But I don’t think the problem you describe is in the Date Format library code (which many people are using successfully). If you can isolate a problem in this library (i.e., which line is causing the issue), that would be helpful. Thanks.

  8. Thanks. I think you’re right. The project is using the .NET AJAX framework and Telerik controls which are importing lots of associated javascript files that probably contain the var conflict. bummer.

  9. @burl, you could try using the dateFormat function instead of its Date.prototype.format alias (see the examples at the top of this post), but beyond that, I can’t help with troubleshooting library conflicts. ๐Ÿ™

  10. I got it to work – and you were correct in assuming .NET has a conflict the the Date.prototype.format in its framework library. To avoid any other naming conflicts, I renamed the class util_dateFormat and inlined all of the code in the needed page.

  11. i was looking for a function that would take a poorly formatted date string that any random user may type in and make an attempt to parse it.

    for example, all of the following would return 1/1/09 (assuming the use of the shortDate format in the script above)

    1/1 -> 01/01/09
    jan 1 -> 01/01/09
    1-1-09 -> 01/01/09

    i don’t think this script is meant to take various formats that users may type and ‘fix’ them. am i missing something? anyone have an alternative script?

  12. Thanks very much for this handy functions – I just started with Javascript and simply could not believe that something so simple has to be coded by hand. You saved me a lot of time.

  13. I plan to include this in an open source environment I’ll be releasing for the first time in Sept.

    Suggestion: “MIT License” is quite vague, and probably doesn’t legally apply the terms of that license to your code. Could you elaborate? ๐Ÿ™‚ At least include a link to the MIT document!

  14. ive got a script below:

    var m = document.lastModified; var p = m.length-8; var d = m.substring(p, 0);

    document.write(d);
    // End –>

    how to i change the date to be of dd/mm/yy format instead of mm/dd/yy what it is in now? ive tried the text above but it doesnt work

  15. Thanks for the very useful script! It’s great to be able to do this kind of intuitive formatting without having to deal with all the bugs and quirks of Datejs.

  16. I think this is a beautiful script. Was wondering if it was possible (and if so, how?) to convert something like 2009-09-11T11:30:00-07:00 to September 11, 2009 11:30am

  17. Hi Steven,

    I am a noob when it comes to using JavaScript, so this may seem like a very basic question…. but here goes.

    I’m trying to figure out how to convert this long form string into just the time part (HH:MM AM or PM: 2009-09-18 15:45:15

    The “s.at” below is the variable that contains the string to be converted. How would I call your function and where should your function go (external, header or embedded in the script from which the line below was taken)?

    CODE SNIP: html += “”+s.at+” “+s.by+” – “+s.title+””;

    Code was provided by YES.Com’s API

  18. Here are the german internationalizations:

    dayNames: [
    “So”, “Mo”, “Di”, “Mi”, “Do”, “Fr”, “Sa”,
    “Sonntag”, “Montag”, “Dienstag”, “Mittwoch”, “Donnerstag”, “Freitag”, “Samastag”
    ],
    monthNames: [
    “Jan”, “Feb”, “Mรƒยคr”, “Apr”, “Mai”, “Jun”, “Jul”, “Aug”, “Sep”, “Okt”, “Nov”, “Dez”,
    “Januar”, “Februar”, “Mรƒยคrz”, “April”, “Mai”, “Juni”, “Juli”, “August”, “September”, “Oktober”, “November”, “Dezember”
    ]

  19. date.dateFormat(“H:M:s”);
    00:Oct:00

    date.dateFormat(“H:m:s”);
    16:10:12

    but the “10” correpond to octobre and not to the hours … why ?

  20. Hi. Thank you so much for your work on this set of functions. It’s really very excellent and useful. You’ve saved me a lot of time.

    In Firefox your function throws a syntax error with the input in the form “mm-dd-yyyy”. In Chrome and I’m guessing Safari, this works fine.

    This is a pretty nasty fix but it works. (at line 36):

    EDIT: It’s not letting me post the code, so here it is
    http://pastebin.com/f1797361d

    It replaces the “-“s with “/”s. It works for my purposes, but I don’t know if it would be good in general.

    Again, thank you very much. Is leaving your license/name heading in the file sufficient for crediting you?

  21. Steve,

    Excellent work! Got one question; I am not too familar with the MIT License; but can I add this to my commercial application? Anything else I needed to add to my application to meet the MIT license for using this? Many Thanks!

    Ofcourse, I will include the follow comments:

    /*
    * Date Format 1.2.3
    * (c) 2007-2009 Steven Levithan
    * MIT license
    *
    * Includes enhancements by Scott Trenda
    * and Kris Kowal
    *
    * Accepts a date, a mask, or a date and a mask.
    * Returns a formatted version of the given date.
    * The date defaults to the current date/time.
    * The mask defaults to dateFormat.masks.default.
    */

  22. @skyrun, yeah, this library is not designed to parse date strings; it formats dates as strings. It’s parsing responsibilities are merely passed off to the native Date constructor methods (see https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference/Global_Objects/Date/parse ).

    @Luciano A. Ferrer, what is the error? Is it saying you provided an invalid date? ๐Ÿ™‚ Keep in mind that, as noted above, this library does not have robust date parsing (which is simply passed off to whatever the browser supports natively). Generally, it’s safer to provide an actual date object to the function; not a date-like string.

    @Liam Breck, whatever. It’s well understood that an unqualified “MIT License” refers exclusively to the “X11 license” (if you prefer the less common and less recognizable name). See http://en.wikipedia.org/wiki/MIT_License , etc.

    @fuultier, thanks for that!

    @Tyler, see my comments to skyrun and Luciano A. Ferrer above. This is not (currently, anyway) a date parsing library, beyond a few basic formats that can be handled by the native Date constructors cross-browser. And yes, including the credits in the source file is sufficient.

    @Sam, yes, including those credits is enough. ๐Ÿ™‚

    Thanks, all!

  23. Brillant!
    some simple things are always brillant. I needed to get the date in the UTC format et voila!
    Great Job

    Thanks

  24. Steve,

    Kudos on the code; I’ve learned quite a bit perusing through and deconstructing it.

    I’m using dateFormat for some code that talks with Google’s GData services, Google Calendar in particular. Google’s API barfs when the offset is -0500 but works fine with -05:00 (see the start-max and start-min params in the URL):

    http://j.mp/6r7mdo (correct)
    http://j.mp/59kLcZ (error)

    Consequently I’ve added a new flag:

    O: (o > 0 ? “-” : “+”) + pad(Math.floor(Math.abs(o) / 60), 2) + “:” + pad(Math.abs(o) % 60, 2)

    Thanks

  25. Hi!

    I did some changes in the source code to allow multi i18n.

    The default culture is english. If you want to add more culture, add a JS file with the object’s array filled.

    How can I send you the code for proposal?

    Thanks

  26. @Vincent Bergeron, you could email me (email address on the About page), but probably a better route would be to use a service like pastebin and link to the code here. That way other people can see/use the code before I add it or if I decide not to include it in the library. Thanks!

  27. Good day,

    I’ll appreciate it if somebody can assist with the following query…

    Using the dateFormat javascript command in IDE, I manage to successfully select most of the date links when recording and playback. However, in some instances we have date links which have exactly the same dates, but each link refers to different pages. (i.e. different attached emails).

    Using the HTML tags I could identify that eg. Date 1 = “25 January 20101” and Date 2 = “25 January 20102″, but I battle to find the correct dateFormat which will allow me to select the required Date 1 or Date 2 when the actual dates are the same.

    The following script will always select the first occurrence (Date 1):

    store|javascript{dateFormat(dateTodayPlusDays(0),”dd mmmm yyyy”)}|aLink
    clickAndWait|link=${aLink}

    Regards
    Amor

  28. Awesome code – thank you!

    How can I modify to include the Quarter (i.e. Q1 = Jan, Feb and Mar, Q2 = Apr, May, Jun, etc).

    I want to be able to do a format mask to show Q1 – 2009, Q2 – 2009, etc or the long way: Quarter 1 – 2009, Quarter 2 – 2009, etc.

    Please help.

  29. @flocsy, thanks for sharing that.

    @James, to add support for quarters (digit 1–4, via the mask Q), change the [LloSZ] character class in the token regex to [LloSZQ], and add Q: Math.ceil((m + 1) / 3) to the flags object.

    After that, you should be able to use something like dateFormat("'Q'Q - yyyy") or dateFormat("'Quarter' Q - yyyy").

  30. I wonder how do I go from 12 hours format to 24 hour format

    eg 10:00 AM to make this 10:00:00

    thanks

  31. saludos, el otro estube buscando como formatear la salida de fechas en javascript, y se me ocurio migrar la funciรณn http://www.devtics.com.mx/wp/index.php/238-funcion-date-para-formatear-salida-de-fechas-en-javascript/ date() de PHP a JavaScript, y aquรญ se las dejo, se maneja exactamente = que date en php ๐Ÿ™‚ espero le sirva , me faltaron migrar algunos parametros, ya que se me complicaron un poco o bien no entendia bien como obtenerlos o no entendia en que se usaba, pero esta un 70% migrada y se puden usar los formatos mas usuales

Leave a Reply

Your email address will not be published. Required fields are marked *