Moment.js - how do I get the number of years since a date, not rounded up?

JavascriptDateMomentjs

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

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.

Solution 2 - Javascript

http://jsfiddle.net/xR8t5/27/

if you do not want fraction values:

var years = moment().diff('1981-01-01', 'years',false);
alert( years);

if you want fraction values:

var years = moment().diff('1981-01-01', 'years',true);
alert( years);

Units can be [seconds, minutes, hours, days, weeks, months, years]

Solution 3 - Javascript

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

Solution 4 - Javascript

This method is easy and powerful.

Value is a date and "DD-MM-YYYY" is the mask of the date.

moment().diff(moment(value, "DD-MM-YYYY"), 'years');

Solution 5 - Javascript

I found that it would work to reset the month to January for both dates (the provided date and the present):

> moment("02/26/1978", "MM/DD/YYYY").month(0).from(moment().month(0))
"34 years ago"

Solution 6 - Javascript

Try this:

 moment("02/26/1978", "MM/DD/YYYY").fromNow().split(" ")[0];

Explanation:

We receive string something like this: '23 days ago'. Split it to array: ['23', 'days', 'ago'] and then take first item '23'.

Solution 7 - Javascript

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

Solution 8 - Javascript

If you dont want to use any module for age calculation

var age = Math.floor((new Date() - new Date(date_of_birth)) / 1000 / 60 / 60 / 24 / 365.25)

Solution 9 - Javascript

When you want to show years and the remaining days:

var m = moment(d.birthday.date, "DD.MM.YYYY");
var years = moment().diff(m, 'years', false);
var days = moment().diff(m.add(years, 'years'), 'days', false);
alert(years + ' years, ' + days + ' days');

Solution 10 - Javascript

I prefer this small method.

function getAgeFromBirthday(birthday) {
    if(birthday){
      var totalMonths = moment().diff(birthday, 'months');
      var years = parseInt(totalMonths / 12);
      var months = totalMonths % 12;
        if(months !== 0){
           return parseFloat(years + '.' + months);
         }
    return years;
      }
    return null;
}

Solution 11 - Javascript

Get years and days using moment.js library

import moment from 'moment'

export function getAge(dateString: string) {
  const date = moment(dateString, 'YYYY-MM-DD')
  const years = moment().diff(date, 'years')
  const days = moment().diff(date.add(years, 'years'), 'days', false)
  return { years, days }
}

const birthDate = "1997-04-01T00:00:00.000Z";
const age = getAge(birthDate);

// Today is 2022-04-09
console.log({ age })
// Result: { age: { years: 25, days: 8 } }

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionaknuds1View Question on Stackoverflow
Solution 1 - JavascriptEdwin BeltranView Answer on Stackoverflow
Solution 2 - JavascriptRazan PaulView Answer on Stackoverflow
Solution 3 - Javascriptuser4815162342View Answer on Stackoverflow
Solution 4 - Javascriptuser2327748View Answer on Stackoverflow
Solution 5 - Javascriptaknuds1View Answer on Stackoverflow
Solution 6 - JavascriptFyodor KhruschovView Answer on Stackoverflow
Solution 7 - JavascriptRickard AnderssonView Answer on Stackoverflow
Solution 8 - JavascriptAnkitView Answer on Stackoverflow
Solution 9 - JavascriptXdgView Answer on Stackoverflow
Solution 10 - JavascriptDagan Bog-ComputersView Answer on Stackoverflow
Solution 11 - JavascriptEmanuelView Answer on Stackoverflow