How to format a duration in years and months?

I'm using node.js w/ moment.js for formatting times. I want to get a patient's age formatted in months and years. Here's what I've got so far:

patient: {
    ...
    birthDate: moment('Dec 15, 2009'),
    getAgeString: function() {
        var age = moment.duration(moment() - this.birthDate);
        return util.format('%d years, %d months', age.years(), age.months());
    }
}

The getAgeString function gives me back 3 years, 1 months, which is pretty close to what I want, except I'd like it to be pluralized properly. As far as I can tell, moment doesn't offer proper pluralization for durations.

this.birthDate.fromNow(true) is "smart" but it doesn't seem to offer any customization options as to what gets displayed.

Can I get moment.js to do what I want, or is there a better time library for node?


This will have to do for now:

getAgeString: function() {
    var age = moment.duration(moment() - this.birthDate);
    var years = age.years(), months = age.months();
    return util.format('%d year%s, %d month%s', years, years === 1 ? '' : 's', months, months === 1 ? '' : 's');
}

The words that you are looking to pluralize properly appear to be string literals in your own code, and not based on the formatting module. You could do a conditional age.years() or age.months() are equal to 1. If they are, use the strings "year" or "month", otherwise use "years" or "months".