簡體   English   中英

我可以通過momentjs得出年份和月份中兩個日期之間的差額嗎?

[英]Can I get the difference between two dates in years and months with momentjs?

以下內容會給我幾年和幾個月的時間:

var years = toDate.diff(todaysDate, 'years');
var months = toDate.diff(todaysDate, 'months');

因此,如果相差2年2個月,我將得到:

2
14

我可以使用矩來獲得這種格式的差異嗎?

2 years, 2 months

由於您不想添加其他插件,因此可以使用模數運算符%將月份轉換為正確的值。

這是一個工作示例:

 var todaysDate = moment(); var toDate = moment().add(14, 'months'); var years = toDate.diff(todaysDate, 'years'); var months = toDate.diff(todaysDate, 'months'); console.log(years + ' years, ' + months % 12 + ' months'); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.13.0/moment.min.js"></script> 

使用矩持續時間格式的另一種解決方案如下:

 var todaysDate = moment(); var toDate = moment().add(14, 'months'); var months = toDate.diff(todaysDate, 'months'); var duration = moment.duration(months, 'months'); console.log(duration.format("y [years] M [months]")); 
 <script src="//cdnjs.cloudflare.com/ajax/libs/moment.js/2.14.1/moment.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/moment-duration-format/1.3.0/moment-duration-format.min.js"></script> 

這樣,您可以根據月份值創建一個工期對象,然后使用插件根據需要對其進行格式化。

暫時還沒有。 我知道他們正在使用格式化持續時間的插件,但不要指望很快就會發布該插件。

https://github.com/moment/moment/issues/1048

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM