在JQuery中获取上个月的第一个和最后一个日期
我有这个脚本,
var today = new Date();
var dd = today.getDate();
var ddd = today.getDate()-1;
var dddd = today.getDate()-2;
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10){
dd='0'+dd
}
if(mm<10){
mm='0'+mm
}
if(ddd<10){
ddd='0'+ddd
}
var today = dd+'/'+mm+'/'+yyyy;
var d2 = ddd+'/'+mm+'/'+yyyy;
var d3 = dddd+'/'+mm+'/'+yyyy;
有了这个,我获得当天的最后3天,但在这种情况下今天是02如果我休息两天我得到0但我想在这种情况下是上个月的最后一天,怎么办呢?
With this i obtain the last 3 days of the current day but in this case today is 02 if i rest two days i obtain 0 but i want in this case the last day of the previous month, how can do this?
这是我的小提琴
这是第一次当前月份的一天新日期(now.getFullYear(),now.getMonth(),1)
获取上个月的最后一天创建日期1天之前:新日期(now.getFullYear(),now.getMonth(),1 - 1)
。
That's the first day of the current month new Date(now.getFullYear(), now.getMonth(), 1)
to get the last day of the previous month create a date 1-day earlier: new Date(now.getFullYear(), now.getMonth(), 1 - 1)
.
要获得上个月的第一天,我们应该从月份组件新日期(now.getFullYear(),now.getMonth() - 1,1)
中减去1,但是如果当前月份是1月(0)而前一个月是12月(11),则会出现问题。因此,我将月份表达式包装成一个循环,因此它总是返回一个positiove值。
To get the first day of the previous month we should substract 1 from the month component new Date(now.getFullYear(), now.getMonth() - 1, 1)
but there is an issue if the current month is January (0) and the previous month is December (11). Hence I wrapped the month expression creating a cycle so it always returns a positiove value.
var now = new Date();
var prevMonthLastDate = new Date(now.getFullYear(), now.getMonth(), 0);
var prevMonthFirstDate = new Date(now.getFullYear() - (now.getMonth() > 0 ? 0 : 1), (now.getMonth() - 1 + 12) % 12, 1);
var formatDateComponent = function(dateComponent) {
return (dateComponent < 10 ? '0' : '') + dateComponent;
};
var formatDate = function(date) {
return formatDateComponent(date.getMonth() + 1) + '/' + formatDateComponent(date.getDate()) + '/' + date.getFullYear();
};
document.write(formatDate(prevMonthFirstDate) + ' - ' + formatDate(prevMonthLastDate));