I'm trying to calculate a person's age using Moment.js, but I'm finding that the otherwise useful fromNow method rounds up the years. For instance, if today is 12/27/2012 and the person's birth date is 02/26/1978, moment("02/26/1978", "MM/DD/YYYY").fromNow()
returns '35 years ago'. How can I make Moment.js ignore the number of months, and simply return the number of years (i.e. 34) since the date?
152
votes
10 Answers
259
votes
Using moment.js is as easy as:
var years = moment().diff('1981-01-01', 'years');
var days = moment().diff('1981-01-01', 'days');
For additional reference, you can read moment.js official documentation.
37
votes
22
votes
There appears to be a difference function that accepts time intervals to use as well as an option to not round the result. So, something like
Math.floor(moment(new Date()).diff(moment("02/26/1978","MM/DD/YYYY"),'years',true)))
I haven't tried this, and I'm not completely familiar with moment, but it seems like this should get what you want (without having to reset the month).
13
votes
10
votes
8
votes
3
votes
This method works for me. It's checking if the person has had their birthday this year and subtracts one year otherwise.
// date is the moment you're calculating the age of
var now = moment().unix();
var then = date.unix();
var diff = (now - then) / (60 * 60 * 24 * 365);
var years = Math.floor(diff);
Edit: First version didn't quite work perfectly. The updated one should
2
votes
1
votes
1
votes