dayjs diff between two date in day and hours

Ömer Doğan picture Ömer Doğan · Mar 15, 2021 · Viewed 7.6k times · Source

I wanna calculate the difference between the two dates with dayjs library. 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. but there are hours that are not calculated inside 'item'. I mean it should be like '20 days 9 hours'.

How can I do this with dayjs?

Thanks for any helps

Answer

0stone0 picture 0stone0 · Mar 15, 2021
  1. Get the difference in hours
  2. Divide (and round) hours by 24 to get the days
  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/[email protected]/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?