views:

4420

answers:

4

if you provide 0 as the dayValue in Date.setFullYear you get the last day of the previous month:

d = new Date(); d.setFullYear(2008, 11, 0); //  Sun Nov 30 2008

There is reference to this behaviour at mozilla. Is this a reliable cross-browser feature or should I look at alternative methods?

+1  A: 

No, not all browsers will use 0 as the last day. IE and Firefox will but Opera will not.

Check out the following source for more info:

Last day of Month

SaaS Developer
I'm not sure that observation is accurate. See my results, specifically those for Opera 8.54, 9.27 and 9.60.
Grant Wagner
+5  A: 

I would user an intermediate date with the first day of the next month, and return the date from the previous day.

Something like this :


int_d = new Date(2008, 11+1,1);
d = new Date(int_d - 1);
m_oLogin
+7  A: 
var month = 0; // January
var d = new Date(2008, month + 1, 0);
alert(d); // last day in January

IE 6: Thu Jan 31 00:00:00 CST 2008
IE 7: Thu Jan 31 00:00:00 CST 2008
IE 8: Beta 2: Thu Jan 31 00:00:00 CST 2008
Opera 8.54: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.27: Thu, 31 Jan 2008 00:00:00 GMT-0600
Opera 9.60: Thu Jan 31 2008 00:00:00 GMT-0600
Firefox 2.0.0.17: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Firefox 3.0.3: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Google Chrome 0.2.149.30: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)
Safari for Windows 3.1.2: Thu Jan 31 2008 00:00:00 GMT-0600 (Canada Central Standard Time)

Output differences are due to differences in the toString() implementation, not because the dates are different.

Of course, just because the browsers identified above use 0 as the last day of the previous month does not mean they will continue to do so, or that browsers not listed will do so, but it lends credibility to the belief that it should work the same way in every browser.

Grant Wagner
That seems to work perfectly well. Out of curiosity, what are you using to run the javascript on all these engines? Got everything set-up or some kind of tool?
neonski
+2  A: 

According to the ECMAScript specification, making use of the "Date" constructor as you pointed out is valid. Following the algorithm specified by the "MakeDay" function, it should handle the issue nicely.

Pablo Cabrera