本文介绍了如何从now.js正确添加1个月到当前日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我阅读了moment.js的文档,如果你想从当前日期时间加1个月,你可以使用这段代码
var moment = require('moment');
var futureMonth = moment()。add(1,'M')。format('DD-MM-YYYY');
但问题是现在,它没有正确添加日期,例如
假设当前日期是2015年10月31日,在代码中解释
var currentDate = moment()。format('DD -MM-YYYY');
var futureMonth = moment()。add(1,'M')。format('DD-MM-YYYY');
console.log(currentDate)//将结果 - > 31/10/2015
console.log(futureMonth)//将结果 - > 30/11/2015
如果您查看当前日历时间,距离<$ 1个月c $ c> 31/10/2015 应该 2015年1月12日
谢谢
解决方案
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);
编辑
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());
I read the documentation of moment.js that if you want to add 1 month from the current date time you use this code
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 examplelet say the current date is 31/10/2015, explain in code
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/2015
supposed to be 1/12/2015
Could anyone give me some opinion on how to fix this problem.
Thank you
解决方案
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);
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());
这篇关于如何从now.js正确添加1个月到当前日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!