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

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?

This question is related to javascript date momentjs

The answer is


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


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.


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');

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;
}

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]


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


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');

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)

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


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to momentjs

How to get am pm from the date time string using moment js Vuejs and Vue.set(), update array How to subtract one month using moment.js? Get timezone from users browser using moment(timezone).js Check if date is a valid one moment.js get current time in milliseconds? Deprecation warning in Moment.js - Not in a recognized ISO format Moment js get first and last day of current month Moment get current date Moment.js - How to convert date string into date?