读书人

怎么获得上个月

发布时间: 2012-02-16 21:30:36 作者: rapoo

如何获得上个月?
alert(currentDate.getFullYear()+'-'+ (currentDate.getMonth()+1) +'-'+currentDate.getDate());

以上弹出当月年月日

我想准确弹出上个月的年月日如何做?
例现在是2007-12-18

想弹出2007-11-18

看过一些方法是在当前年月日里减30天,但这样做并不准确,当月为2时可能是28天,有些月会31天.如何做才行?



[解决办法]

JScript code
 
Date.prototype.getDayOfMonth = function(Mm){
var Feb = (this.getFullYear() % 4 == 0)?29:28;
var aM = new Array(31, Feb , 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
return (typeof Mm == 'undefined')?aM[this.getMonth()-1]:aM[Mm-1];
};
Date.prototype.getDateOfPreMonth = function(){

return new Date(
(this.getMonth() == 0)?(this.getFullYear()-1):this.getFullYear() ,
(this.getMonth() == 0)?11:this.getMonth() ,
this.getDayOfMonth(
(this.getMonth() == 0)?11:(this.getMonth()-1)
<=
this.getDate()
)?this.getDate():
this.getDayOfMonth(
(this.getMonth() == 0)?11:(this.getMonth()-1)
)

);
};
var d = new Date().getDateOfPreMonth();
alert(d);

读书人网 >JavaScript

热点推荐