我正试图形成一个日期,这是3个月前的当前日期。我通过下面的代码得到当前月份

var currentDate = new Date();
var currentMonth = currentDate.getMonth()+1;

你能给我提供一个逻辑来计算和形成一个日期(date数据类型的对象),考虑到当月份是一月(1)时,日期前3个月将是十月(10)吗?


当前回答

d.setMonth在浏览器try中修改了本地时间

 const calcDate = (m) => {
    let date = new Date();
    let day = date.getDate();
    let month = date.getMonth() + 1;
    let year = date.getFullYear();
    let days = 0;

    if (m > 0) {
      for (let i = 1; i < m; i++) {
        month += 1;
        if (month > 12) {
          year += 1;
          month = 1;
        }
        days += new Date(year, month, 0).getDate();
      }
    } else {
      for (let i = m; i < 0; i++) {
        month -= 1;
        if (month < 1) {
          year -= 1;
          month = 12;
        }
        days -= new Date(year, month, 0).getDate();
      }
    }

    const newTime = date.getTime() + 3600 * 24 * 1000 * days;
    return new Date(newTime);
  };

calcDate(3)//+3 month

其他回答

这应该可以处理加法/减法,只需输入一个负数来做减法,一个正值来做加法。这也解决了月份交叉的问题。

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;    
}

已经有了一个优雅的答案,但我发现它很难读,所以我自己做了一个函数。出于我的目的,我不需要一个消极的结果,但它也不难修改。

    var subtractMonths = function (date1,date2) {
        if (date1-date2 <=0) {
            return 0;
        }
        var monthCount = 0;
        while (date1 > date2){
            monthCount++;
            date1.setMonth(date1.getMonth() -1);
        }
        return monthCount;
    }

由于“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复制和粘贴!您可以自己开发代码来完成您所需要的工作!

在我的例子中,我需要减去1个月到当前日期。重要的部分是月号,所以它不关心你在本月的哪一天,我需要上个月。这是我的代码:

var dateObj = new Date('2017-03-30 00:00:00'); //Create new date object
console.log(dateObj); // Thu Mar 30 2017 00:00:00 GMT-0300 (ART)

dateObj.setDate(1); //Set first day of the month from current date
dateObj.setDate(-1); // Substract 1 day to the first day of the month

//Now, you are in the last month
console.log(dateObj); // Mon Feb 27 2017 00:00:00 GMT-0300 (ART)

减去1个月到实际日期是不准确的,这就是为什么在第一个地方我设置了一个月的第一天(任何一个月的第一天总是第一天),在第二个地方我减去1天,这总是把你送到上个月。 希望能帮到你,伙计。

var dateObj = new Date('2017-03-30 00:00:00');//创建新的日期对象 console.log (dateObj);// 2017年3月30日星期四00:00:00 GMT-0300 (ART) dateObj.setDate (1);//从当前日期开始设置月的第一天 dateObj.setDate (1);//每月的第一天减1 //现在是最后一个月 console.log (dateObj);// 2017年2月27日星期一00:00:00 GMT-0300 (ART)

这样做

 let currentdate = new Date();
 let last3months = new Date(currentdate.setMonth(currentdate.getMonth()-3));

Javascript的setMonth方法也负责年份。例如,如果currentDate设置为new Date("2020-01-29"),上述代码将返回2020-01-29。