Click here to Skip to main content
Licence 
First Posted 16 Jul 2005
Views 154,272
Bookmarked 46 times

JavaScript Date Format

By | 7 Aug 2005 | Article
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:

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):

// 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 (not shown) prefixes 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. Behave and I may supply the prototype.
  • 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 has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here

About the Author

hector.j.rivas

Software Developer (Senior)

United States United States

Member

Hector J. Rivas has 25+ years of experience managing hardware and software development under many different operating systems, platforms and languages. He has developed microcontroller interfaces and PC games; authored computer based training lessons and delivered fully functional financial and administrative data-intensive applications, as well as image processing and other calculation-intensive applications. Mr. Rivas has also managed Y2K remediation, large scale platform migration and Web site projects, from R&D to actual deployment.

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board. (secure sign-in)
 
Search this forum  
 FAQ
    Noise  Layout  Per page   
  Refresh
GeneralPutting it all together so far Pinmembermurray5616:15 2 Mar '07  
GeneralRe: Putting it all together so far Pinmembermurray5617:09 2 Mar '07  
GeneralRe: Putting it all together so far PinmemberTor2k20:09 4 Mar '07  
GeneralRe: Putting it all together so far Pinmembermurray5621:49 5 Mar '07  
Generalhey PinmemberFrenaaa8:09 3 Dec '06  
GeneralRe: hey PinmemberTor2k7:22 8 Dec '06  
GeneralEasy but useful PinmemberNinghuan22:01 25 Apr '06  
GeneralC#-like formats PinmemberKjetil Klaussen23:15 8 Mar '06  
GeneralZF PinmemberTunez1:09 1 Aug '05  
GeneralRe: ZF PinmemberTor2k14:00 2 Aug '05  
GeneralA couple of bugs PinmemberRichard Deeming7:08 26 Jul '05  
GeneralRe: A couple of bugs PinmemberTor2k10:42 26 Jul '05  
GeneralRe: A small addition PinmemberDougww3:13 5 Aug '05  
GeneralRe: A small addition PinmemberTor2k7:16 6 Aug '05  
GeneralRe: A small addition PinmemberRichard Deeming2:21 10 Aug '05  
GeneralRe: A small addition PinmemberTor2k6:18 10 Aug '05  
GeneralRe: A small addition Pinmembershadowcreeper10:05 20 Apr '09  
GeneralRe: A small addition PinmemberTor2k5:47 21 Apr '09  
GeneralRe: A small addition: string 'choose' io switch PinmemberTor2k9:30 8 Aug '05  
Ok, I changed the 'sup' format specifier with 's/p' and replaced the switch with a math operation:
 
case 's/p': var i = d.getDate() % 10; return 'thstndrd'.substr(2 * (i < 4) * i, 2);
 
You see, i (date mod 10) ranges from 0 to 9, but only 1, 2 and 3 have specific ordinal suffixes, so with a little math, and in a fashion similar to a choose statement in VB, I got rid of the switch statement for (hopefully) faster execution.
 
The math goes as follows: (i < 4) yields true for 0, 1, 2, 3 and false for everything else; fortunately for us, booleans yield 1 or 0 when used in arithmetic operations (in VB, 'true' actually equals -1). So this simple expression filters out the 'uninteresting' cases.
 
Next, we need the actual i value to pinpoint each case, that's why we multiply. This is also why we calculate and store i ahead of time, for we'll use it twice in the expression.
 
The rest involves doubling the value to get a 2-char index into the strange string we sub into, which is nothing but the ordinal suffixes, th st nd rd.
 
Incidentally, I realized you would need another date specifier to avoid presenting '06th', that is, skip the zero fill. But then again this datepart specifier itself might be enough (or maybe a 5d, ddddd that is) if you simply prepend the date.
 
Again, I just had fun figuring out an alternative to the switch. Richard Deeming corrected this anyway by pointing out that we'll get 11st i.o. 11th, 12nd and 13rd which are totally wrong; I guess the switch is in order, or an even messier math op.

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.

Permalink | Advertise | Privacy | Mobile
Web04 | 2.5.120529.1 | Last Updated 8 Aug 2005
Article Copyright 2005 by hector.j.rivas
Everything else Copyright © CodeProject, 1999-2012
Terms of Use
Layout: fixed | fluid