Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add day to date with momentjs

Tags:

date

momentjs

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?

like image 230
Trung Tran Avatar asked Dec 05 '22 12:12

Trung Tran


2 Answers

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().

like image 68
VincenzoC Avatar answered Jan 19 '23 03:01

VincenzoC


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;

like image 43
gem007bd Avatar answered Jan 19 '23 01:01

gem007bd