问题描述
我正在寻找一种方法来使用momentjs来解析两个日期,以显示差异。
I'm looking for a way to use momentjs to parse two dates, to show the difference.
我希望格式化:X years ,Y个月,Z天。
I want to have it on the format: "X years, Y months, Z days".
对于年和月,库和模运算符的工作效果很好。但是对于那些日子来说这是另一个故事,因为我不想处理闰年和我自己的所有这些。到目前为止,我脑子里的逻辑是:
For the years and months the moment library and modulo operator works nice. But for the days it's another tale as I don't want to handle leap years and all that by myself. So far the logic I have in my head is this:
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'years');
var months = a.diff(b, 'months') % 12;
var days = a.diff(b, 'days');
// Abit stuck here as leap years, and difference in number of days in months.
// And a.diff(b, 'days') returns total number of days.
return years + '' + months + '' + days;
推荐答案
您可以在几年内获得差异并将其添加到初始日期;然后在几个月内得到差异并再次将其添加到初始日期。
You could get the difference in years and add that to the initial date; then get the difference in months and add that to the initial date again.
这样做,您现在可以轻松获得天数差异,并避免使用模数运算符。
In doing so, you can now easily get the difference in days and avoid using the modulo operator as well.
var a = moment([2015, 11, 29]);
var b = moment([2007, 06, 27]);
var years = a.diff(b, 'year');
b.add(years, 'years');
var months = a.diff(b, 'months');
b.add(months, 'months');
var days = a.diff(b, 'days');
console.log(years + ' years ' + months + ' months ' + days + ' days');
// 8 years 5 months 2 days
我不知道更好,内置的方法来实现这一点,但这种方法似乎运作良好。
I'm not aware of a better, built-in way to achieve this, but this method seems to work well.
这篇关于Moment.js - 在两年,几个月和几天的生日中获得差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!