简体   繁体   English

使用 Moment.js 将 2 个日期之间的差异转换为 'y mod d' 格式

[英]Convert the difference between 2 dates to 'y mo d' format using Moment.js

I am running into a wall trying to figure out how to convert the difference between two dates to an accurate breakdown of how many years, months and days it's been since the start date.我遇到了一个难题,试图弄清楚如何将两个日期之间的差异转换为自开始日期以来已经过了多少年、几个月和几天的准确细分。 The format I want to show is: '1y 5mo 2d' given two dateTimes that have that difference.我要显示的格式是:'1y 5mo 2d' 给定两个具有这种差异的日期时间。 I tried using Moment.js and it works pretty well for 'y' and 'mo' but I am running into a wall trying to figure out how to accurately get the number of days.我尝试使用 Moment.js,它对于 'y' 和 'mo' 效果很好,但我遇到了困难,试图弄清楚如何准确地获得天数。

export const convertDaysToYMD = (dates: {start, end})=>{
  const start = Moment(dates.start)
  const end = Moment(dates.end)
  const y = end.diff(start, 'years')
  const m = end.diff(start, 'months')
  const d = end.diff(start, 'days')
  console.log('y', y + ' m', m%12 + ' d', d)
}

I can accuratly get the number of years and then the number of months by using mod(12) but due to the number of days changing per month I don't quite know how to get the number of days.我可以通过使用 mod(12) 准确地获得年数和月数,但由于每月变化的天数,我不太清楚如何获得天数。 Any help would be great.任何帮助都会很棒。

You can use moment's duration method like this:您可以像这样使用时刻的duration方法:

 const start = moment('2020-01-02'); const end = moment('2020-02-03'); const duration = moment.duration(end.diff(start)); console.log(`${duration.years()} years ${duration.months()} months and ${duration.days()} days.`)
 <script src="https://momentjs.com/downloads/moment.min.js"></script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM