12

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

Ömer Doğan
  • 501
  • 1
  • 6
  • 21
  • 2
    Get the difference in seconds, then convert those to the desired format (days/hours) – 0stone0 Mar 15 '21 at 14:22
  • Does this answer your question? [Difference between two time using dayjs](https://stackoverflow.com/questions/60226101/difference-between-two-time-using-dayjs) – 0stone0 Mar 15 '21 at 14:23
  • 1
    Get the difference in hours and then convert it into days and hours. – Hassan Imam Mar 15 '21 at 14:26

3 Answers3

25
  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/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?

0stone0
  • 34,288
  • 4
  • 39
  • 64
  • 1
    Not all days are 24 hours long where daylight saving is in use, so this method is not always accurate. There are a huge number of questions and answers already on the [difference between two dates](https://stackoverflow.com/search?q=%5Bjavascript%5D+difference+between+two+dates). – RobG Mar 15 '21 at 22:13
5

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/dayjs@1.8.21/dayjs.min.js"></script>
Pablo Lozano
  • 10,122
  • 2
  • 38
  • 59
0

${dayjs(item).diff(now, 'hour') day} instead of ${dayjs(item).diff(now, 'day') day}

That second parameter is the unit of measurement to use and you set it to day

s123
  • 102
  • 9