Flagrant Badassery

A JavaScript and regular expression centric blog

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.


New library: Are you a JavaScript regex master, or want to be? Then you need my fancy XRegExp library. It adds new regex syntax (including named capture and Unicode properties); s, x, and n flags; powerful regex utils; and it fixes pesky browser inconsistencies. Check it out!

There Are 534 Responses So Far. »

  1. First, if I can say, reading the examples you mentioned on this blog is very inspiring. Thank you for creating this list.

  2. Goodness, I truly preferred this page. As a fledgling, it truly invigorated me a ton of.

  3. ?????????????????????????????????????????????????????????????????????????????????

    ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????5 ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    1.????????????????????????????????????????????????
    ?????????????????????????????. ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    2.?????????????????????????????????????????????????
    ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    3.????????????????????????????????????????
    ????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????.???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    4.????????????????????????????????????SEO ???????????
    ??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????google ???????????????????????????SEO ???????????????????????????????????

    5.??????????????????????????????????????????????????????
    ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    ???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

    ???????? https://www.articleheros.com

  4. Are you facing any problem in using the Garmin map? Do you got stuck somewhere on road and the device is not working properly? Don’t be afraid we are here to resolve your all concerns. Just pick up your phone, make a call and leave all your worries on us.

  5. Webroot SecureAnywhere Antivirus is more than antivirus software. It is antimalware. It stops the viruses and worms that exist in order to infect other computers, but it also protects you during web surfing sessions by blocking harmful websites. And it takes down spyware that tries to deceive you or exploit vulnerabilities in operating systems. Download and Install Webroot security on your computer.

  6. Webroot.com/safe is the only security solution which can protect your system from viruses, worms, malware threats. Get Webroot safe today & install on your system and say goodbye to viruses.

  7. To figure out how to HBO go com activate range, you can go with expert assistance. The help out there is given by proficient technical support specialists who have profound information about the HBO Go range.

  8. Helpful source to clarify all issues quickly.

  9. You’re no longer beholden to cable subscription and if you want a wide range of television options to get Roku device today start watching TV on upon Roku device activation by visiting roku.com/link.

  10. Your Post very useful and I share your post on my websites and group.
    You can visit my website to read more blogs about Roku device, Roku device activation, and Roku error or troubleshooting problems.
    roku.com/link

  11. Your blogs and post is all time famous and popular. your content writing skills very nice. for this, I share your blogs on my group, blogs.
    I support all Roku users and you can visit my website for roku.com/link setup, Roku error, and troubleshooting problems.

    roku.com/link

  12. Oooh Woow, your post is great. I am very happy and I share your post on my social groups, my blogs. Your content skills are very amazing.
    I am also a blogger and I help Roku users who face problem Roku activation, roku.com/link setup and more. Please visit our website once time.

    roku.com/link

  13. AVG is the one of best antivirus which protects your computer and network from bad infection and threats. AVG now includes real-time security updates, scans for both malware and performance issues, and even catches malicious downloads before they reach your PC. User can Install AVG Antivirus on their computer to protect thier computer and network…

  14. AVG AntiVirus is a family of antivirus software developed by AVG Technologies, a subsidiary of Avast. It is available for Windows, macOS and Android. AVG ensuring your safety and security online. In AVG features, most of the common functions available in modern antivirus and Internet security programs, including periodic scans. AVG Online Shield also ensures the safety of exchanging files via instant messengers and VoIP clients.

  15. AVG line-up combines effective malware eradication with fast scans and just about every security feature you could wish for. Simply activate AVG license and install AVG on your system to keep your system protected.

  16. It is very helpful to secure your device and it is very light weighted antivirus product.
    Webroot secure anywhere offers a user-friendly interface which provides several functions & they all work together to make a system protected. To activate Webroot go to webroot.com/safe
    Webroot security is a great antivirus program, which amazingly lightweight tool with accurate URL blocking and powerful bonus features.

  17. Want expert help to Activate Roku? For Roku Activation, you can dial Customer Service Number Roku at US/Canada Toll-Free: +1 844-756-1728 and get help from Streaming Guides. We also provide Roku Troubleshooting for issues like Roku Com/Link Setup, Activate Roku Com/Link, Roku Com Link Create Account, Roku Update, Roku Error Code 001, Error Code 018 on Roku, Roku Error Code 009, Roku Won’t Connect to WiFi, and more.

    https://streaminguides.com/roku-activation/

  18. Thanks for support

    https://www.mctwebhelp.com/ufaqs/how-to-recover-my-yahoo-account-password-without-phone-number/

  19. Very nice blog

    https://www.getphonelist.com/phone-number/roku/

  20. By dropping them an email regarding to the problem on their official email address- In this process, drop a mail consisting your entire problem clearly.

    https://www.dating-advisors.com/how-do-i-cancel-tinder-plus-membership-and-get-a-refund/

  21. How to Setup Your Device Through Roku.com/link ?
    Lets connect your device @ https://www.howaboutfacts.com/roku-com-link-code-activation/

  22. Usually, I never comment on blogs, but his article is so compelling that I never stop talking about it. You’re fine, man, keep it up.

  23. This blog is a great source of information. We can all contribute and benefit from reading, as well as gain knowledge about this content, just an incredible experience.

  24. We are the dedicated service provider in the dating industry. Keep in mind, assistance like us is nearly impossible to experience with anybody else. Please remember! we are the independent service provider.

  25. […] JavaScript Date Format […]

  26. Having read this I believed it was extremely informative. I appreciate you taking the time and effort to put this information together. I once again find myself spending way too much time both reading and commenting. But so what, it was still worth it!

  27. The very next time I read a blog, I hope that it doesn’t disappoint me just as much as this particular one. I mean, I know it was my choice to read, but I actually thought you would probably have something interesting to talk about. All I hear is a bunch of whining about something you can fix if you weren’t too busy looking for attention.

  28. Get unlimited access to the Hulu streaming library with limited
    ads. Enjoy full seasons of exclusive series, hit movies, Hulu Originals, kids shows, and more.
    Stream 60+ top Live and On Demand TV channels including sports, news, and entertainment.
    Record Live TV with 50 hours of Cloud DVR storage.

    http://hulucomhuluu.com

  29. I am realy very happy , when i read your blogs, You are working good for any customer for find a right way for any help please keep it up and do best from your aside.

  30. Great Information regarding trust and citation flow, ill try to incorporate this into my website for better rankings . Cheers!

  31. Thank you for creating such a website
    I want to make my business successful
    God bless you too

  32. At&t Corporation used to be a popular digital electronics manufacturer that is best known for its networking equipment. The company always had its prime focus around Ethernet technology, which is why it used to have major focus on all kinds of networking equipment. The company was taken over by HP in the year 2010, and since then the company has just been its part and has ceased to exist as a separate entity. Those who need any assistance their At&t device can now reach out to HP’s own At&t Customer Service team to have their issue resolved.

  33. I really like your blog. It helped me a lot. Entire details were given with easy to understand words. I wish you the best of luck for your future endeavors

  34. HI~ This site is really good.
    I will visit again next time. There’s a lot of information here.
    There’s a lot to see and read. Thank you.

  35. ????? ??????? ??????? ?????? Dota 2 CS:GO

    https://vk.com/trade_network

    Trade Network, ????? ?????? ???????, ???? ? ????, ??????? ?????? ?????, ??????? ?????? ?????, ?????? ???????, ????? ???? ?????

  36. The information you shared is wonderful to me, thank you and have a nice day. You can also search for information at Magical World

  37. Great Information regarding trust and citation flow, ill try to incorporate this into my website for better rankings . Cheers!

  38. Dial Now Netgear Router Support Number 1855-834-2055 For Immediate Assistance. We commit our prosperity to our customer. We are capable of delivering the device and its answers for our clients and keep they’re separate private and business clients associated with proficient and fulfilled outcomes.

  39. Do You Any Need To Download HP Printer Drivers For HP Printers? Visit Here…
    If you want to know how you can download HP printer drivers for Windows or you are facing some technical issues with your HP printer due to printer drivers, you can easily get immediate solutions with the help of our professionals at HP Printer Support Phone Number. They will provide you immediate solutions for printer drivers regarding HP Printers Drivers Downloads. Our experts will always there for you so that you can quickly resolve all your issues. This will be the best way for you by which you can easily download HP drivers.

  40. Webroot SecureAnywhere Antivirus is more than antivirus software. It is antimalware. It stops the viruses and worms that exist in order to infect other computers, but it also protects you during web surfing sessions by blocking harmful websites. And it takes down spyware that tries to deceive you or exploit vulnerabilities in operating systems. Download and Install Webroot security on your computer by visit: https://answer-webroot.com/

  41. Present norton antivirus with the best help gathering and keep your PC contamination free. Download norton norton install with product key antivirus with the best help gathering and avoid disease attacks.

  42. norton help to ensure your gadgets against antiviruses and offer security to client and giving personality and contraption affirmation to your related life.visit; norton install with product key here.

  43. norton internet security is widely used antivirus provides the easiest to use and most intutive protection for your computer and your mobiles .install it and forget about viruses,spyware,root-kits, hackers.for more details visit:norton install with product key here.

    Norton.com/setup

  44. Norton Antivirus is the best internet security that protects your data and device from being lost and damaged. Get your Norton Products started today. Visit norton.com/setup.

  45. […] Use the date.format library: […]

  46. Roku Error Code Setup – Call us at +1-888-623-9203 to Setup your roku com link account error. Resolve the issue(s) or seek help from Roku contact support by visiting our official website

  47. To experience a flawless streaming experience and setup roku code error, Call a toll-free Roku support number +1-877-214-8174. We are available to help 24/7 to setup Roku Device

  48. Thanks for sharing, I now know a little bit more about javascript using in webpage especially at using date format.

  49. Guidelines to Troubleshoot Roku Error Code 009

  50. How to Fix Roku Error Code 003?

Post a Response

If you are about to post code, please escape your HTML entities (&amp;, &gt;, &lt;).