Click here to Skip to main content
15,867,568 members
Articles / Programming Languages / Javascript

JavaScript Date Format

Rate me:
Please Sign up or sign in to vote.
4.61/5 (25 votes)
3 Dec 2012CPOL2 min read 277.5K   68   26
A fast VB-like date format function in JavaScript (requires JScript 5.5+).

Introduction

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:

JavaScript
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.

Implementation

WOFA, (Without Further Adou):

JavaScript
// a global month names array
var gsMonthNames = new Array(
'January',
'February',
'March',
'April',
'May',
'June',
'July',
'August',
'September',
'October',
'November',
'December'
);
// a global day names array
var gsDayNames = new Array(
'Sunday',
'Monday',
'Tuesday',
'Wednesday',
'Thursday',
'Friday',
'Saturday'
);
// 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,
        function($1)
        {
            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';
            }
        }
    );
}

Notes

  • 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.

Enjoy.

License

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


Written By
Software Developer (Senior) Texas Capital Bank
United States United States
Professional software engineer with 30+ years of experience delivering systems across diverse industries, looking for the next opportunity to deliver cutting edge end-to-end technology solutions.

Avid reader, disciplined writer and enthusiastic tinkerer with a background in electronics, looking inside and thinking outside the box, genuinely passionate about robust, extensible, reusable and performant code.

Framework developer leading, coaching and learning about best practices, code quality, DevOps and software and data lifecycle management with an agile mindset to create the most elegant and sustainable solutions.

Comments and Discussions

 
Questionfor month part if u put mmm it is returning 000 Pin
Keerthi Kumar(Andar)16-Apr-15 0:24
Keerthi Kumar(Andar)16-Apr-15 0:24 
GeneralMy vote of 5 Pin
Niral Soni29-Jan-13 5:34
Niral Soni29-Jan-13 5:34 
GeneralMy vote of 4 Pin
Mario Majčica3-Dec-12 3:40
professionalMario Majčica3-Dec-12 3:40 
GeneralRe: My vote of 4 Pin
hector [.j.] rivas3-Dec-12 4:18
hector [.j.] rivas3-Dec-12 4:18 
GeneralRe: My vote of 4 Pin
Mario Majčica3-Dec-12 4:21
professionalMario Majčica3-Dec-12 4:21 
GeneralRe: My vote of 4 Pin
hector [.j.] rivas3-Dec-12 4:27
hector [.j.] rivas3-Dec-12 4:27 
GeneralPutting it all together so far Pin
murray562-Mar-07 16:15
murray562-Mar-07 16:15 
GeneralRe: Putting it all together so far Pin
murray562-Mar-07 17:09
murray562-Mar-07 17:09 
GeneralRe: Putting it all together so far Pin
hector [.j.] rivas4-Mar-07 20:09
hector [.j.] rivas4-Mar-07 20:09 
GeneralRe: Putting it all together so far Pin
murray565-Mar-07 21:49
murray565-Mar-07 21:49 
Generalhey Pin
Frenaaa3-Dec-06 8:09
Frenaaa3-Dec-06 8:09 
Jai! ai am javin som trobel loguin in to mai jotmeil acaunt. it sims dat mai pasbuord is not ricognaisd, iven doug ai meid shur dat ol de lirel lait bulbs on mai kibord ar torned on (including the guan coled caps loc)
ai guonder if llu can jelp mi bicos llu jav writen so meni artikels so ai gues llu jav jotmeil tu....

it guas very jard tu faind llu, BUT I DID SO I AM F***ING AWESOME!!! THE MINE SO BIG SO THE MINE SO FINE SO TOR2K QUE ARRECHO EL CD QUE ME MANDASTE!!! DIOS TE BENDIGA HIJO MIOOOOOOOOO! SO BIGGGGGGG!!! D.A.R.E. JAJAJAJA A3VT! LOVIN YA INZA! U CAN RUN BUT YOU CANT HIDE! JAJAJA,

there is no spoon.

PD. FREEEEENAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA!!!
GeneralRe: hey Pin
hector [.j.] rivas8-Dec-06 7:22
hector [.j.] rivas8-Dec-06 7:22 
GeneralEasy but useful Pin
Ninghuan25-Apr-06 22:01
Ninghuan25-Apr-06 22:01 
GeneralC#-like formats Pin
Kjetil Klaussen8-Mar-06 23:15
Kjetil Klaussen8-Mar-06 23:15 
GeneralZF Pin
wickedtuner1-Aug-05 1:09
wickedtuner1-Aug-05 1:09 
GeneralRe: ZF Pin
hector [.j.] rivas2-Aug-05 14:00
hector [.j.] rivas2-Aug-05 14:00 
GeneralA couple of bugs Pin
Richard Deeming26-Jul-05 7:08
mveRichard Deeming26-Jul-05 7:08 
GeneralRe: A couple of bugs Pin
hector [.j.] rivas26-Jul-05 10:42
hector [.j.] rivas26-Jul-05 10:42 
GeneralRe: A small addition Pin
Dougww5-Aug-05 3:13
Dougww5-Aug-05 3:13 
GeneralRe: A small addition Pin
hector [.j.] rivas6-Aug-05 7:16
hector [.j.] rivas6-Aug-05 7:16 
GeneralRe: A small addition Pin
Richard Deeming10-Aug-05 2:21
mveRichard Deeming10-Aug-05 2:21 
GeneralRe: A small addition Pin
hector [.j.] rivas10-Aug-05 6:18
hector [.j.] rivas10-Aug-05 6:18 
GeneralRe: A small addition Pin
shadowcreeper20-Apr-09 10:05
shadowcreeper20-Apr-09 10:05 
GeneralRe: A small addition Pin
hector [.j.] rivas21-Apr-09 5:47
hector [.j.] rivas21-Apr-09 5:47 
GeneralRe: A small addition: string 'choose' io switch Pin
hector [.j.] rivas8-Aug-05 9:30
hector [.j.] rivas8-Aug-05 9:30 

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

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