SimpleDateFormat

Download the code

This was inspired by the need for date formatting while implementing log4j's PatternLayout in a project I'm working on that provides an implementation of log4j in JavaScript, called log4javascript.

I have only implemented a simple format method that takes a Date object and returns a formatted version of it. Every pattern letter except z is implemented; I don't believe the information necessary to implement z is easily available in JavaScript. See Java's SimpleDateFormat documentation for details of all the possible pattern letters.

UPDATE 6 September 2006

In the course of working on log4javascript I discovered that the previous implementation didn't work in Internet Explorer 5 on Windows because the exec method of regular expressions doesn't respect the global flag in IE5. There was also a bug affecting the implementation of pattern letters w and W. These problems were fixed in version 1.3 of log4javascript.

UPDATE 6 February 2007

Thanks to Ash Searle and a fairly rigorous unit test against the output of Java's SimpleDateFormat, I have discovered and fixed some errors, most of which stemmed from my misinterpretation of the Java documentation. Specifically, I had k and h completely wrong, and I was also doing the wrong thing for the three digit year pattern yyy (which should show the two digit year). There were also some bugs due to my forgetting about Daylight Saving Time in calculating time intervals. These are all fixed in the soon-to-be-released log4javascript 1.4, and I've updated the standalone version here.

I believe that this version works in all Mozilla-based browsers including Netscape 6+ and Firefox / Firebird / Phoenix, IE5+ (Windows; untested on the Mac), Konqueror 3+, Safari 1.3+, Opera 7+. I'm sure it works on earlier versions of most of these browsers too, I just haven't been able to test on everything.

Examples

Code:

var sdf = new SimpleDateFormat("yyyy.MM.dd G 'at' HH:mm:ss");
document.write(sdf.format(new Date()));

sdf = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z");
document.write(sdf.format(new Date()));

Output: