我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?
我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份
var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;
你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?
当前回答
如果gilly3提供的setMonth方法不是你想要的,可以考虑:
var someDate = new Date(); // add arguments as needed
someDate.setTime(someDate.getTime() - 3*28*24*60*60);
// assumes the definition of "one month" to be "four weeks".
可以使用任何数量的时间,只要设置正确的倍数。
其他回答
这应该可以处理加法/减法,只需输入一个负数来做减法,一个正值来做加法。这也解决了月份交叉的问题。
function monthAdd(date, month) {
var temp = date;
temp = new Date(date.getFullYear(), date.getMonth(), 1);
temp.setMonth(temp.getMonth() + (month + 1));
temp.setDate(temp.getDate() - 1);
if (date.getDate() < temp.getDate()) {
temp.setDate(date.getDate());
}
return temp;
}
对于今天之前三个月的获取日期:
let d = new Date(new Date().setMonth(new Date().getMonth() - 3))
console.log(d.toISOString().slice(0, 10))
// 2022-05-24 (today is 2022-08-24)
我喜欢gilly3的简单回答,但用户可能会惊讶于3月31日之前的一个月是3月3日。我选择实现一个坚持月底的版本,所以3月28日、29日、30日和31日之前的一个月都是2月28日,因为不是闰年。
function addMonths(date, months) { var result = new Date(date), expectedMonth = ((date.getMonth() + months) % 12 + 12) % 12; result.setMonth(result.getMonth() + months); if (result.getMonth() !== expectedMonth) { result.setDate(0); } return result; } var dt2004_05_31 = new Date("2004-05-31 0:00"), dt2001_05_31 = new Date("2001-05-31 0:00"), dt2001_03_31 = new Date("2001-03-31 0:00"), dt2001_02_28 = new Date("2001-02-28 0:00"), result = addMonths(dt2001_05_31, -2); console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString()); result = addMonths(dt2001_05_31, -3); console.assert(dt2001_02_28.getTime() == result.getTime(), result.toDateString()); result = addMonths(dt2001_05_31, 36); console.assert(dt2004_05_31.getTime() == result.getTime(), result.toDateString()); result = addMonths(dt2004_05_31, -38); console.assert(dt2001_03_31.getTime() == result.getTime(), result.toDateString()); console.log('Done.');
为了让事情变得简单,你可以使用DateJS,一个JavaScript的日期库:
http://www.datejs.com/
示例代码:
Date.today().add({ months: -1 });
由于“2月31日”自动转换为“3月3日”或“3月2日”,作为“3月31日”的前一个月,这是相当违反直觉的,我决定按照我的想法来做。 类似于@Don Kirkby的回答,我也将日期修改为目标月份的最后一天。
function nMonthsAgo(date, n) {
// get the target year, month, date
const y = date.getFullYear() - Math.trunc(n / 12)
const m = date.getMonth() - n % 12
let d = date.getDate()
if (d > 27) { // get a valid date
const lastDateofMonth = new Date(y, m + 1, 0).getDate()
d = Math.min(d, lastDateofMonth)
}
return new Date(y, m, d)
}
d = new Date('2022-03-31')
nMonthsAgo(d, 1).toLocaleDateString()
最后,我喜欢@gilly3在他的回答中说的:
如果您的需求比这更复杂,请使用一些数学并编写一些代码。你是一个开发人员!你不需要安装一个库!你不需要从stackoverflow复制和粘贴!您可以自己开发代码来完成您所需要的工作!