Monday, October 5. 2009
Broken Date.format in Microsoft ASP.NET 2.0 AJAX
The most recent version of the Microsoft ASP.NET 2.0 AJAX Extensions 1.0 (1.0.61025 according to the support info. in Add/Remove programs) has a bug that just bit me. This library adds a format function to the Date object which provides support for Date and Time Format Strings comparable to the .NET implementation. This is a very handy feature, given JavaScript's lack of a built-in date formatting function. But, if you are going to use it, be careful about the following bug: The time zone offset formats have incorrect sign. For example, if you are in the Pacific Time Zone at UTC-8, Date.format will return formats with UTC+8 (which matches the sign of JavaScript's Date.getTimezoneOffset method).
I created a workaround for the websites that I maintain which does not reimplement Date.format (and likely introduce new bugs) nor require any changes to existing code (with one exception - noted below). This code is a horrible hack and I am almost too embarrassed to post it... but not quite. Here it is:
(function() {
var dfmt;
function fixedDateFormat(format) {
var gto = Date.prototype.getTimezoneOffset;
try {
Date.prototype.getTimezoneOffset = function() { return -gto.call(this); }
return dfmt.call(this, format);
} finally {
Date.prototype.getTimezoneOffset = gto;
}
}
var fixfails = 0;
function fixIt() {
dfmt = Date.prototype.format;
if (typeof(dfmt) != "function") {
// If the library has not been loaded yet, defer
if (++fixfails < 3)
setTimeout(fixIt, 100);
return;
}
if (new Date().getTimezoneOffset() > 0 == new Date().format("zz") > 0)
Date.prototype.format = fixedDateFormat;
}
fixIt();
})();
Just include this code somewhere on the page and it will wrap the Date.format function and negate Date.getTimezoneOffset so that the formatted offset is correct. The significant limitation of the code is that if it is included before Date.format is defined, it will wait for the code to load and try again later. The problem with this approach is that code which is run after Date.format is defined before the fix is installed will still trigger the bug and it will be hard to figure out why that code is not working. Therefore, if possible, include this code immediately after the Microsoft AJAX extensions JavaScript is loaded on the page. Alternatively, use your own workaround or avoid using any of the "z" specifiers in your custom format strings.