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

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

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


当前回答

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

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

其他回答

Following code give me Just Previous Month From Current Month even the date is 31/30 of current date and last month is 30/29/28 days:

   <!DOCTYPE html>
<html>
<body>

<p>Click the button to display the date after changing the month.</p>

<button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {

var d = new Date("March 29, 2017"); // Please Try the result also for "March 31, 2017" Or "March 30, 2017"
var OneMonthBefore =new Date(d);

OneMonthBefore.setMonth(d.getMonth(),0);
if(OneMonthBefore.getDate() < d.getDate()  )
{
d.setMonth(d.getMonth(),0);
}else
{
d.setMonth(d.getMonth()-1);

}

    document.getElementById("demo").innerHTML = d;
}
</script>

</body>
</html>

我建议使用一个名为Moment.js的库。

它经过了良好的测试,可以跨浏览器和服务器端工作(我在Angular和Node项目中都使用它)。它对区域日期有很好的支持。

http://momentjs.com/

var threeMonthsAgo = moment().subtract(3, 'months');

console.log(threeMonthsAgo.format()); // 2015-10-13T09:37:35+02:00

.format()返回ISO 8601格式的日期字符串表示形式。你也可以像这样使用自定义日期格式:format('dddd, MMMM Do YYYY, h:mm:ss a')

for (let monthOfYear = 0;monthOfYear < 12;monthOfYear + +) { const maxDate = new Date(); const minDate = new Date(); const max = maxDate.setMonth(maxDate.getMonth() - (monthOfYear - 1), 0); const min = maxDate.setMonth(minDate.getMonth() - (monthOfYear), 1); console.log('max: ',新的日期(max)); console.log('min: ', new Date(min)); }

这是最小和最简单的代码。

   var minDate = new Date(); 
   minDate.setMonth(minDate.getMonth() - 3);

声明具有当前日期的变量。 然后通过使用setMonth内置函数,我们可以得到3个月后的日期。

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