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

13

174

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?

Mallissa answered 27/12, 2012 at 16:0 Comment(0)
M
14

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"
Mallissa answered 27/12, 2012 at 16:14 Comment(1)
In moment.js v2.3.1 there is a .fromNow() method which can also be helpful.Phalarope
P
306

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.

Petrinapetrine answered 24/2, 2014 at 22:4 Comment(1)
If someone needs the number of years in float: var years = moment().diff('1981-01-01', 'years', true); // returns 40.43Alialia
A
48

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]

Absorbed answered 24/6, 2016 at 0:16 Comment(1)
This technique is covered by @ebeltran's answer, and your discussion of fractional values has nothing to do with the question. I'd rather add it as a comment.Mallissa
U
24

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

Uncloak answered 27/12, 2012 at 18:1 Comment(2)
It appears you do not need to receive the floating point number from moment and then round it yourself, for this scenario. It looks like moment is correctly rounding the result for the year calculation using diff.Chichi
From the docs, since 2.0.0, moment#diff will return number rounded down, so you only need to : age = moment().diff(birthDate, 'years') .Joubert
C
17

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');
Caddric answered 23/12, 2016 at 21:46 Comment(0)
M
14

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"
Mallissa answered 27/12, 2012 at 16:14 Comment(1)
In moment.js v2.3.1 there is a .fromNow() method which can also be helpful.Phalarope
T
8

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

Tonguelash answered 12/6, 2014 at 16:11 Comment(1)
This post is being automatically flagged as low quality because it is only code. Would you mind expanding it by adding some text to explain how it solves the problem?Geosphere
C
4

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

Culprit answered 12/4, 2013 at 12:59 Comment(2)
This worked for me if i changed the days of the year to 365.25 to account for leap yearsStereoisomer
using 365.25 is an approximation that can end up in tears - type cal 1752 to see whySherlock
S
2

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)
Sot answered 9/6, 2016 at 5:4 Comment(0)
B
1

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');
Boob answered 6/2, 2018 at 12:54 Comment(0)
I
1

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 } }
Irritability answered 9/4, 2022 at 20:20 Comment(0)
B
1

You can try this:

moment
.duration({
  years: moment(Date.now()).diff(datetime, "years", false),
})
.humanize()
Bombe answered 10/7, 2022 at 13:24 Comment(0)
C
0

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;
}
Chronometry answered 28/1, 2019 at 8:0 Comment(2)
Exactly what I was looking for!Charron
Be careful with string concatenation here. This will consider 11 months to be .11 of a year, i.e. Less than 9 months .9Jambeau
T
0

Here is the simple one using moment.js

let dt = dob;

        let age = '';

        let bY = Number(moment(dt).format('YYYY')); 
        let bM = Number(moment(dt).format('MM')); 
        let bD = Number(moment(dt).format('DD')); 

        let tY = Number(moment().format('YYYY')); 
        let tM = Number(moment().format('MM')); 
        let tD = Number(moment().format('DD')); 


        age += (tY - bY) + ' Y ';

        if (tM < bM) {
            age += (tM - bM + 12) + ' M ';
            tY = tY - 1;
        } else {
            age += (tM - bM) + ' M '
        }

        if (tD < bD) {
            age += (tD - bD + 30) + ' D ';
            tM = tM - 1;
        } else {
            age += (tD - bD) + ' D '
        }
        
        //AGE MONTH DAYS
        console.log(age);
Tinstone answered 30/5, 2022 at 23:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.