How do I get the time difference between two different dates variables, specifically in years, months and days using moment.js?
I found this method but I keep getting weird results. Sometimes the result is one month ahead so I added a subtract one months part to make the result correct, but when the difference between the two dates can be divided into whole years it then becomes a month behind, but then if I remove the subtract month part, it gets even more out of whack.
Also I would like to format it as "X Years, Y Months, Z days", but also can't figure out how to format it in such way.
var dateOne = new Date(2000,07,16); var dateTwo = new Date (1990,07,16); var updatedDate = moment(dateOne).format('ll'); var x = moment(dateOne, 'DD/MM/YYYY').diff(moment(dateTwo, 'DD/MM/YYYY')) var y = moment.duration(x); var why = moment(x).subtract(1, 'M'); var z = Math.floor(y.asYears()) + moment.utc(why).format('/MM/DD'); console.log(z);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script>
Try this perhaps?
var firstDate = moment();
var secondDate = moment("2018-03-19");
var yearDiff = firstDate.diff(secondDate, "year");
var monthDiff = firstDate.diff(secondDate, "month");
var dayDiff = firstDate.diff(secondDate, "day");
console.log(yearDiff + " Years, " + monthDiff + " Months, " + dayDiff + " Days");
As stated by others in the comments, you can't format a duration as a date and since dateOne
and dateTwo
are a Date objects, there is no need for the second argument in moment(dateOne, 'DD/MM/YYYY')
, simply use moment(Date)
.
Moverover, please note that when you use new Date(year, monthIndex, day)
monthIndex
starts from 0, see MDN docs :
The argument
monthIndex
is 0-based. This means thatJanuary = 0
andDecember = 11
.
You can use moment-duration-format plug-in to format momentjs duration according your needs, see format()
docs on the plug-in page .
Here a live sample:
var dateOne = new Date(2000, 7, 16); var dateTwo = new Date(1990, 7, 16); var diff = moment(dateOne).diff(moment(dateTwo)) var dur = moment.duration(diff); var result = dur.format(); console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.24.0/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/2.2.2/moment-duration-format.min.js"></script>
Moment is having a method called .diff() Use that one. https://momentjs.com/docs/#/displaying/difference/
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.