Community Pick: Many members of our community have endorsed this article.
Editor's Choice: This article has been selected by our editors as an exceptional contribution.

Can I have a date?

HonorGodSoftware Engineer
CERTIFIED EXPERT
Published:
Updated:
No!  Not that kind of date. :-)  That wasn't meant to be a pick up line.

This article is about displaying dates in different formats regardless of the browser being used.  If you let the browser's JavaScript engine format a date object for you, there is a wide variation of the output.  For example:

document.write( new Date( '12:34:56 7/8/9' ) )

Open in new window


Results in the following variations (at least on my machine):

  Chrome (2.0.172.28) = Wed Jul 08 2009 12:34:56 GMT-0400 (Eastern Daylight Time)
  IE (8.0.6001.18702IC) = Thu Jul 8 12:34:56 EDT 1909
  FireFox (3.5)    = Thu Jul 08 1909 12:34:56 GMT-0400 (Eastern Daylight Time)

Note: The different browsers interpret a single digit year differently!

What's an easy way to have the output include:

- The day of the week
- The month of the year, and
- Two digit values (where appropriate)?

This seems to work in a fairly straight-forward way:

function formatDate( val ) {
                        function D2( val ) {
                          return ( val < 10 ) ? '0' + val : val
                        }
                      
                        var DoW = 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split( ',' )
                        var MoY = 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split( ',' )
                      
                        return DoW[ val.getDay() ]    + ' ' +
                               MoY[ val.getMonth() ]  + ' ' +
                               D2( val.getDate() )    + ', ' +
                               val.getFullYear()      + ' ' +
                               D2( val.getHours() )   + ':' +
                               D2( val.getMinutes() ) + ':' +
                               D2( val.getSeconds() )
                      }

Open in new window


Consequently, the altered example document.write( formatDate( new Date( '12:34:56 7/8/9' ) ) ) results in:

Wed Jul 08, 2009 12:34:56

Open in new window

or
Thu Jul 08, 1909 12:34:56

Open in new window

depending upon how the browser's JavaScript engine interprets a date of '7/8/9'.

Ok, this is a start.  What about other formats?  There are lots of ways to format a date. Isn't there some way that we can collect all of these different format styles into a nice and easy to use function?

That's what this article is about.  Let's first consider some extra date-related utility functions that can also prove to be useful.  We already saw one (i.e., "D2()") above.  D2() can be used to add a leading '0' to a number (if necessary) in order to guarantee that the result is 2 digits long.  This routine is very simple, and includes no error checking (e.g., is the value passed a number?).  Anyway, what other utility routines may prove useful while dealing with dates?

In a similar fashion to D2() this routine, D3(), can be used to generate a 3 digit (numeric) value.  Note how it uses D2() to convert a single digit value into two digits.

function D3( val ) {
                        var result = '' + D2( val );
                        return ( result.length < 3 ) ? '0' + result : result;
                      }

Open in new window


This routine, LongDay(), can be used to convert a short day name (e.g., "Mon") into its long equivalent (i.e., "Monday")

var Days = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split( ',' );
                      function LongDay( Day ) {
                        for ( var d = 0; d < Days.length; d++ ) {
                          if ( Day == Days[ d ].substr( 0, 3 ) ) {
                            return Days[ d ];
                          }
                        }
                        return '';
                      }

Open in new window


And this routine, LongMonth(), works similar to the LongDay() function except for month names.

var Months = 'January,February,March,April,May,June,July,August,September,October,November,December'.split( ',' );
                      function LongMonth( Mon ) {
                        for ( var m = 0; m < Months.length; m++ ) {
                          if ( Mon == Months[ m ].substr( 0, 3 ) ) {
                            return Months[ m ];
                          }
                        }
                        return '';
                      }

Open in new window


Another useful function is one that displays the time portion of a date object in military time format (i.e., 00:00 through 23:59).  As you can see, it too makes use of the D2() function defined earlier.

function Military( date ) {
                        return D2( date.getHours() ) + ':' + D2( date.getMinutes() );
                      }

Open in new window


What about the day of year?  One of the methods that seems to be missing from the date object is one that returns the day of the year for a given date.  One way that we can correct that oversight is to define getDOY() as a prototype function of the Date object.  This way, it can be used, just getMonth(), or getDate() to return the day of the year (1..366) for a given date.

Date.prototype.getDOY = function() {
                        var Jan1st = new Date( this.getFullYear(), 0, 1 );
                        return Math.ceil( ( this - Jan1st ) / 86400000 ) + 1;
                      }

Open in new window


Alright, now that we have a bunch of utility routines defined, how can we put them all together into a usable function that can be used to format a date object in a variety of ways?

Well, rather than include that code here in the article text, I've just added two files.  One, FormatDate.js, contains the functions shown above, as well as a FormatDateTime() routine that can be used to format a date object using a user specified format string.
FormatDate.js.txt

The other file, FormatTest.html, shows how this external JavaScript file, and the routines that it contains can be used to simplify the formatting of date objects into various representations.
FormatTest.html.txt

In its simplest form, the date format routine (i.e., FormatDateTime()) only needs the following information in order to format a specific date/time into a desired pattern:

- The format string
- The date/time to be formatted

So, how do we use FormatDateTime() routine?  Well, it's really simple.  If we don't specify a date object, or date/time string (i.e., the second parameter), then the routine uses the current date and time.

To format the information, it breaks down the format string into individual pieces, and for the pieces that it recognizes as format patterns, it uses that appropriate portion of the date object using the specified pattern.

To make this clear, let's take a look at a few examples using the attached files.

The top part of the FormatTest.html page shows the various format sequences, and the bottom of the page has two input fields (one for the "Format String", and the other for the "Date String").  If we leave the "Date String" field empty, the current date and time will be used.

The simplest of the format patters fall in the category of "common" format sequences. For example, to format the current date we might be able to use a Format String of "1", the result of which happened to be:

Tuesday, July 14, 2009

Open in new window


Wow.  That's really, really simple.  What if we want to include the time?  If we use a Format String of "2 3" the result is:

07/14/09 11:28 AM

Open in new window


This is really slick. Since the first part of the Format String is a recognized pattern (i.e., "2"), that indicates how the date should be displayed, followed by a single space followed by another known pattern (i.e., "3"), which specifies how the time should be displayed.

The examples, just above the input fields, on the FormatText.html page show various ways to combine the format indicators, and the input fields let you experiment with these to better understand how a date & time will be displayed for a given Format String.

Once you get the hang of it, I think that you too will find this FormatDate module and the FormatDateTime() routine within simple and easy to use.

Good luck & have fun.
5
6,720 Views
HonorGodSoftware Engineer
CERTIFIED EXPERT

Comments (3)

Kevin CrossChief Technology Officer
CERTIFIED EXPERT
Most Valuable Expert 2011

Commented:
Good article, HonorGod.  You have my vote above!
Rajar AhmedConsultant
CERTIFIED EXPERT

Commented:
Hi honorgod ,

i dint find these files in the articles .
FormatDate.js
FormatTest.html

HonorGodSoftware Engineer
CERTIFIED EXPERT

Author

Commented:
@meeran03 : I don't know what happened to the attachments.

I have reported them missing, and will work to get them replaced.

Thanks for pointing this out!

Have a question about something in this article? You can receive help directly from the article author. Sign up for a free trial to get started.