09.09.05
Browser quirk: Safari and the Date object
While working on some date logic yesterday, I discovered that Safari’s implementation of the JavaScript Date object behaves differently than Internet Explorer, Firefox, Mozilla, Opera, etc.
The great thing about the Date object is that you have the ability to set the fields (month, day, year) to values outside of their prescribed ranges. For instance, month is normally set to a value between 0 and 11. If you create a new date:
var myDate = new Date(2005,13,1);
The resulting date will be February 1, 2006, because the Date object will increment the calendar 2 months into the following year.
The problem in Safari arises when using negative values. Take the code below for example:
var myDate = new Date(2005,-1,1);
In most browsers, this date would evaluate to December 31, 2004. However, Safari refuses to decrement the month field into the previous year, even though it will increment into the next year.
Here’s an example that executes on the page:
var date=new Date(2005,-1,1);document.write(date.toDateString()) (Should show “Wed Dec 01 2004″, but not in Safari!)
This bug appears to only apply to the month field. If you set a negative value into the date field, it will decrement as expected, which is a huge relief since calculating the last day of the previous month can be quite irritating.
The moral of the story is that if your Date addition/subtraction code needs to work in Safari, don’t count on negative month values working the same way that they do in other browsers. If you don’t know this, it could really screw things up.
Tags: calendar, css, javascript, safari, web development