Add day to date with momentjs

对着背影说爱祢 提交于 2020-07-16 06:22:08

问题


I am trying to add a day to my date:

let createdDate = moment(new Date()).utc().format();

let expirationDate = moment(createdDate).add(1, 'd');

console.log(expirationDate);

However, this keeps returning an obscure object {_i: "2017-12-20T21:06:21+00:00", _f: "YYYY-MM-DDTHH:mm:ss Z", _l: undefined, _isUTC: false, _a: Array(7), …}

fiddle:

http://jsfiddle.net/rLjQx/4982/

Does anyone know what I might be doing wrong?


回答1:


You are logging a moment object. As the Internal Properties guide states:

To print out the value of a Moment, use .format(), .toString() or .toISOString().

let createdDate = moment(new Date()).utc().format();
let expirationDate = moment(createdDate).add(1, 'd');
console.log(expirationDate.format());
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.20.1/moment.min.js"></script>

Please note that you can get the current date using moment() (no need to use new Date()) or moment.utc().




回答2:


The add method modifies the moment object. So when you log it, you're not getting an obscure object, you're getting the moment object you're working with. Are you expecting a formatted date? Then use format or some other method.




回答3:


I will go with this one, simple works for me and I don't think you need other function to only add day in moment.

var yourPreviousDate = new Date(); var yourExpectedDate = moment(yourPreviousDate).add(1, 'd')._d;




回答4:


I agree with other answers just providing shortcut and different ways

You can do the format at the same time

moment().add(1,'d').format('YYYY-MM-DD');

or you can just format any date or date object

moment(result.StartDate).format('YYYY-MM-DD');


来源:https://stackoverflow.com/questions/47914349/add-day-to-date-with-momentjs

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!