Click here to Skip to main content
Click here to Skip to main content

JavaScript Date Format

, 3 Dec 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
A fast VB-like date format function in JavaScript (requires JScript 5.5+).


I needed a JavaScript date format function such as the Visual Basic Format function, in which you can pass a format string; my first approach was to issue a series of consecutive and "destructive" replace calls, but upon discovering that the 5.5 (or higher) version of JScript supported the use of a function as the replaceText argument of the replace method, I got creative.

Here's an example call of what I wanted:

SomeDiv.innerText = (new Date()).format('dddd, mmmm dd, yyyy.');

This would display:

Saturday, July 16, 2005

So in my first approach, I globally and case-insensitively replaced dddd with the corresponding string, which "destroyed" every occurrence, so that later in the code I could replace dd with the date number.

This worked just fine, but I knew that by inspecting the format specifier for a match, I could skip the search of every format specifier; say I only want the month and the date; well, by switching upon the format specifier (or rather "datepart" specifier), the year replacement will never be issued. Get it?

The fun part relies in the use of a function in the replaceText argument of the replace method; this way the $1 property as a function argument always represents the last match.

Other considerations include the format or "datepart" specifiers: none other than yyyy will be parsed as the year; months and days have the usual three flavors of fullname (mmmm), three-letter (mmm) or numeric (mm); hours (hh) can be rectified to the 12-hour format with the a/p specifier, and minutes (nn) and seconds (ss) may also be specified.


WOFA, (Without Further Adou):

// a global month names array
var gsMonthNames = new Array(
// a global day names array
var gsDayNames = new Array(
// the date format prototype
Date.prototype.format = function(f)
    if (!this.valueOf())
        return ' ';

    var d = this;

    return f.replace(/(yyyy|mmmm|mmm|mm|dddd|ddd|dd|hh|nn|ss|a\/p)/gi,
            switch ($1.toLowerCase())
            case 'yyyy': return d.getFullYear();
            case 'mmmm': return gsMonthNames[d.getMonth()];
            case 'mmm':  return gsMonthNames[d.getMonth()].substr(0, 3);
            case 'mm':   return (d.getMonth() + 1).zf(2);
            case 'dddd': return gsDayNames[d.getDay()];
            case 'ddd':  return gsDayNames[d.getDay()].substr(0, 3);
            case 'dd':   return d.getDate().zf(2);
            case 'hh':   return ((h = d.getHours() % 12) ? h : 12).zf(2);
            case 'nn':   return d.getMinutes().zf(2);
            case 'ss':   return d.getSeconds().zf(2);
            case 'a/p':  return d.getHours() < 12 ? 'a' : 'p';


  • A date with a value of 0 returns a non-breaking space.
  • Notice how the d variable is available to the replacement function (but the this object is not).
  • The zf number prototype can be found in Extending JavaScript Objects with Prototypes, where it is called 'zp' for zero padding. It pads a number with zeroes the specified number of times, up to the number's character length, i.e. 2 turns into 02, but 16 remains 16.
  • The regular expression looks for any of the bracketed pattern characters in a two+ sequence, or for the very specific a/p match.
  • Defining names globally helps and serves other purposes, i.e. listing days in a calendar.



This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

hector [.j.] rivas
Software Developer (Senior) Code Authority, Inc.
United States United States
Pride in craftsmanship is my new thing.
Follow on   LinkedIn

Comments and Discussions

GeneralMy vote of 5 PinmemberNiral Soni29-Jan-13 6:34 
GeneralMy vote of 4 PinmemberMario Majčica3-Dec-12 4:40 
GeneralRe: My vote of 4 Pinmemberhector.j.rivas3-Dec-12 5:18 
GeneralRe: My vote of 4 PinmemberMario Majčica3-Dec-12 5:21 
GeneralRe: My vote of 4 Pinmemberhector.j.rivas3-Dec-12 5:27 
GeneralPutting it all together so far Pinmembermurray562-Mar-07 17:15 
GeneralRe: Putting it all together so far Pinmembermurray562-Mar-07 18:09 
GeneralRe: Putting it all together so far PinmemberTor2k4-Mar-07 21:09 
Another commonly used date parts would be the time zone specifier (GMT, CMT, etc.) and the '07 year format. Please note that the 'x' case may yield 12nd for 12. Be careful with that, try another approach for ordinals...
There is no spoon.

GeneralRe: Putting it all together so far Pinmembermurray565-Mar-07 22:49 
Generalhey PinmemberFrenaaa3-Dec-06 9:09 
GeneralRe: hey PinmemberTor2k8-Dec-06 8:22 
GeneralEasy but useful PinmemberNinghuan25-Apr-06 23:01 
GeneralC#-like formats PinmemberKjetil Klaussen9-Mar-06 0:15 
GeneralZF PinmemberTunez1-Aug-05 2:09 
GeneralRe: ZF PinmemberTor2k2-Aug-05 15:00 
GeneralA couple of bugs PinmemberRichard Deeming26-Jul-05 8:08 
GeneralRe: A couple of bugs PinmemberTor2k26-Jul-05 11:42 
GeneralRe: A small addition PinmemberDougww5-Aug-05 4:13 
GeneralRe: A small addition PinmemberTor2k6-Aug-05 8:16 
GeneralRe: A small addition PinmemberRichard Deeming10-Aug-05 3:21 
GeneralRe: A small addition PinmemberTor2k10-Aug-05 7:18 
GeneralRe: A small addition Pinmembershadowcreeper20-Apr-09 11:05 
GeneralRe: A small addition PinmemberTor2k21-Apr-09 6:47 
GeneralRe: A small addition: string 'choose' io switch PinmemberTor2k8-Aug-05 10:30 
GeneralRe: A small addition: string 'choose' io switch Pinmemberjsc424-Dec-12 23:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 3 Dec 2012
Article Copyright 2005 by hector [.j.] rivas
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid