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

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

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


当前回答

var d = new日期("2013/01/01"); console.log (d.toLocaleDateString ()); d.setMonth(d.getMonth() + 18); console.log (d.toLocaleDateString ());

其他回答

这样做

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

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

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

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>

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

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 oneMonthAgo = new Date(
    new Date().getFullYear(),
    new Date().getMonth() - 1, 
    new Date().getDate()
);