Javascript 如何在moment.js中正确添加从现在到当前日期的1个月

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33440646/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 15:03:37  来源:igfitidea点击:

How to properly add 1 month from now to current date in moment.js

javascriptnode.jsdatemomentjs

提问by Hyman Moscovi

I read the documentation of moment.js that if you want to add 1 month from the current date time you use this code

我阅读了 moment.js 的文档,如果您想从当前日期时间添加 1 个月,请使用此代码

var moment = require('moment');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');

But the problem right now, it is not properly add the date correctly, for example let say the current date is 31/10/2015, explain in code

但是现在的问题,不是正确添加日期,例如假设当前日期是 31/10/2015,在代码中解释

var currentDate = moment().format('DD-MM-YYYY');
var futureMonth = moment().add(1, 'M').format('DD-MM-YYYY');

console.log(currentDate) //  Will result --> 31/10/2015
console.log(futureMonth) //  Will result --> 30/11/2015 

if you take a look at the current calendar time, 1 month from 31/10/2015supposed to be 1/12/2015

如果您查看当前的日历时间,31/10/2015应该是1 个月后1/12/2015

Could anyone give me some opinion on how to fix this problem.

谁能给我一些关于如何解决这个问题的意见。

Thank you

谢谢

回答by silentw

var currentDate = moment('2015-10-30');
var futureMonth = moment(currentDate).add(1, 'M');
var futureMonthEnd = moment(futureMonth).endOf('month');

if(currentDate.date() != futureMonth.date() && futureMonth.isSame(futureMonthEnd.format('YYYY-MM-DD'))) {
    futureMonth = futureMonth.add(1, 'd');
}

console.log(currentDate);
console.log(futureMonth);

DEMO

DEMO

EDIT

编辑

moment.addRealMonth = function addRealMonth(d) {
  var fm = moment(d).add(1, 'M');
  var fmEnd = moment(fm).endOf('month');
  return d.date() != fm.date() && fm.isSame(fmEnd.format('YYYY-MM-DD')) ? fm.add(1, 'd') : fm;  
}

var nextMonth = moment.addRealMonth(moment());

DEMO

DEMO

回答by Anoop M

According to the latest docyou can do the following-

根据最新的文档,您可以执行以下操作-

Add a day

添加一天

moment().add(1, 'days').calendar();

Add Year

添加年份

moment().add(1, 'years').calendar();

Add Month

添加月份

moment().add(1, 'months').calendar();

回答by Anusha Nilapu

You could try

你可以试试

moment().add(1, 'M').subtract(1, 'day').format('DD-MM-YYYY')

回答by nishith

startdate = "20.03.2020";
    var new_date = moment(startdate, "DD-MM-YYYY").add(5,'days');

     alert(new_date)