Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

dayjs diff between two date in day and hours

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

like image 999
Ömer Doğan Avatar asked Mar 15 '21 14:03

Ömer Doğan


2 Answers

  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?

like image 169
0stone0 Avatar answered Oct 16 '22 12:10

0stone0


You can obtain the number of days with decimals (adding true as second parameter to diff and work with it:

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/[email protected]/dayjs.min.js"></script>
like image 42
Pablo Lozano Avatar answered Oct 16 '22 12:10

Pablo Lozano