Skip to main content
Email Password   helpLost your password?

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

Enjoy.

You must Sign In to use this message board.
 
 
Per page   
 FirstPrevNext
GeneralPutting it all together so far Pin
murray56
17:15 2 Mar '07  
GeneralRe: Putting it all together so far Pin
murray56
18:09 2 Mar '07  
GeneralRe: Putting it all together so far Pin
Tor2k
21:09 4 Mar '07  
GeneralRe: Putting it all together so far Pin
murray56
22:49 5 Mar '07  
Generalhey Pin
Frenaaa
9:09 3 Dec '06  
GeneralRe: hey Pin
Tor2k
8:22 8 Dec '06  
GeneralEasy but useful Pin
Ninghuan
23:01 25 Apr '06  
GeneralC#-like formats Pin
Kjetil Klaussen
0:15 9 Mar '06  
GeneralZF Pin
Tunez
2:09 1 Aug '05  
GeneralRe: ZF Pin
Tor2k
15:00 2 Aug '05  
GeneralA couple of bugs Pin
Richard Deeming
8:08 26 Jul '05  
GeneralRe: A couple of bugs Pin
Tor2k
11:42 26 Jul '05  
GeneralRe: A small addition Pin
Dougww
4:13 5 Aug '05  
GeneralRe: A small addition Pin
Tor2k
8:16 6 Aug '05  
GeneralRe: A small addition Pin
Richard Deeming
3:21 10 Aug '05  
GeneralRe: A small addition Pin
Tor2k
7:18 10 Aug '05  
GeneralRe: A small addition Pin
shadowcreeper
11:05 20 Apr '09  
GeneralRe: A small addition Pin
Tor2k
6:47 21 Apr '09  
GeneralRe: A small addition: string 'choose' io switch Pin
Tor2k
10:30 8 Aug '05  


Last Updated 7 Aug 2005 | Advertise | Privacy | Terms of Use | Copyright © CodeProject, 1999-2009