简体   繁体   English

dayjs 在日和小时中的两个日期之间的差异

[英]dayjs diff between two date in day and hours

I wanna calculate the difference between the two dates with dayjs library.我想用 dayjs 库计算两个日期之间的差异。 it works nice but I need to something different a little bit.它工作得很好,但我需要一些不同的东西。 For example:例如:

`${dayjs(item).diff(now, 'day') day}`

this function returns '20 days' or whatever.此 function 返回“20 天”或其他任何内容。 but there are hours that are not calculated inside 'item'.但有些小时不在“项目”内计算。 I mean it should be like '20 days 9 hours'.我的意思是它应该像“20 天 9 小时”。

How can I do this with dayjs?我怎么能用 dayjs 做到这一点?

Thanks for any helps感谢您的帮助

  1. Get the difference in hours以小时为单位获取差异
  2. Devivde (and round) hours by 24 to get the days以 24 小时计算(和循环)小时以获取日期
  3. Get the remainder, those are the left hours得到剩余的,那些是剩下的时间

 const date1 = dayjs('2021-03-13'); const date2 = dayjs(); let hours = date2.diff(date1, 'hours'); const days = Math.floor(hours / 24); hours = hours - (days * 24); console.log('Days: ', days); console.log('Hours: ', hours);
 <script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>


The same logic could be done using seconds, then apply a function to convert those seconds into days/hours/minuts: Convert seconds to HH-MM-SS with JavaScript?可以使用秒来完成相同的逻辑,然后应用 function 将这些秒转换为天/小时/分钟: 使用 JavaScript 将秒转换为 HH-MM-SS?

You can obtain the number of days with decimals (adding true as second parameter to diff and work with it:您可以获得带小数的天数(将true作为第二个参数添加到diff并使用它:

 const date1 = dayjs('2021-03-13'); const date2 = dayjs(); const diff = date2.diff(date1,'day',true); console.log("obtained", diff); const days = Math.floor(diff); const hours = Math.floor((diff - days) * 24); console.log(`${days} days, ${hours} hours`);
 <script src="https://unpkg.com/dayjs@1.8.21/dayjs.min.js"></script>

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

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