gazingus.org

Date Formatting Function

A lot of web sites use client-side JavaScript to display the current date. While all the scripts I have seen that do this are similar, I decided to write a general date formatting script that is both flexible and extendable.

The single method format extends the native Date class. It takes a string argument representing a "mask" to apply the date object, resulting in a human-readable string. Given a Date object now, the following statements:

now.format("MM/DD/YY");
now.format("D MMMM YYYY h:mm:ss tt");
now.format("DDDD, MMMM d");
now.format();

would evaluate to, respectively:

As the last example shows, if no mask is supplied the method uses a default mask. The mask elements are replaced with their corresponding values, while non-mask characters are preserved. Recognized mask elements and their values are as follows:

D       day of the month
d       day of the month with suffix
DD      day of the month, leading zero
DDD     day of the week, abbreviated
DDDD    day of the week, full
M       month number
MM      month number, leading zero
MMM     month name, abbreviated
MMMM    month name, full
Y       year, last digit
YY      year, last two digits
YYYY    year, four digits
H       hour (24-hour)
HH      hour, leading zero (24-hour)
h       hour (12-hour)
hh      hour, leading zero (12-hour)
m       minute
mm      minute, leading zero
s       second
ss      second, leading zero
t       meridian, one character
tt      meridian, two characters

The script can be customized for other languages by altering the three global variables Date.MONTHS, Date.DAYS, and Date.SUFFIXES.