计算每月的最后一天 [英] Calculate last day of month

查看:55
本文介绍了计算每月的最后一天的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果在 Date.setFullYear 中提供 0 作为 dayValue ,则会得到上个月的最后一天:

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

mozilla 上对此行为有参考.这是可靠的跨浏览器功能还是我应该考虑替代方法?

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

推荐答案

var month = 0; // January
var d = new Date(2008, month + 1, 0);
console.log(d.toString()); // 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)

输出差异是由于 toString()实现方式的差异,而不是因为日期不同.

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

当然,仅仅因为上面标识的浏览器将0用作上个月的最后一天,并不意味着它们会继续这样做,或者未列出的浏览器也会这样做,但这为相信它在每种浏览器中都应该以相同的方式工作.

这篇关于计算每月的最后一天的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆