如何在几年和几个月内格式化一个持续时间?

我使用node.js w / moment.js格式化时间。 我想要得到一个病人的年龄格式在几个月和几年。 这是迄今为止我所得到的:

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

getAgeString函数给了我3 years, 1 months ,这是非常接近我想要的,除了我希望它被正确地复数化。 据我所知,时间不能提供适当的复数持续时间。

this.birthDate.fromNow(true)是“聪明的”,但它似乎没有提供任何自定义选项,以显示什么。

我可以得到moment.js做我想做的,还是有一个更好的时间库节点?


这将不得不现在做:

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

你正在寻找复数正确的话似乎是在你自己的代码中的string文字,而不是基于格式化模块。 你可以做一个条件age.years()或age.months()等于1.如果是,使用string“年”或“月”,否则使用“年”或“月”。