Moment.js 計算兩個日期的年月日差異

JeffChang
2 min readOct 6, 2018

--

上網找了找資料,覺得沒有一個比較適合的方法,後來找到一個還不錯的解法,抽取後改寫成方法並記錄。

首先,這次要使用的套件是Moment.js這個套件,

怎麼安裝並使用就不贅述,Moment官方文件有教。

// 這邊範例直接給定日期,有需要傳入變數請自行改寫成方法
const startDate = moment('2017-01-01');
const endDate = moment('2018-01-01');
// 計算兩者差異年數
const years = endDate.diff(startDate, ‘years’);
// 計算兩者差異月數,這邊要扣掉上面計算的差異年,否則會得到12個月
const months = endDate.diff(startDate, ‘months’) - (years * 12);
// 把差異的年、月數加回來,否則會變成計算起訖日相差的天數(365天)
startDate.add(years, 'years').add(months, 'months');
const days = endDate.diff(startDate, 'days');
console.log('years = ', years); // 1
console.log('months = ', months); // 0
console.log('days = ', days); // 0
// 若比較 2017-04-07 & 2018-10-06
// 則年月日差異 1y 5m 29d

這個方法唯一的限制就是 :結束日一定要比起始日大,不然計算出來的會變成負數,不過這應該不是問題,取絕對值就好了。

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

JeffChang
JeffChang

Written by JeffChang

Java Backend Engineer In DDIM.

No responses yet

Write a response