dayjs diff between two date in day and hours
Asked Answered
P

3

18

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

Paul answered 15/3, 2021 at 14:21 Comment(3)
Get the difference in seconds, then convert those to the desired format (days/hours)Pentosan
Does this answer your question? Difference between two time using dayjsPentosan
Get the difference in hours and then convert it into days and hours.Stationery
P
32
  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?

Pentosan answered 15/3, 2021 at 14:40 Comment(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.Glyceryl
S
8

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>
Southernly answered 15/3, 2021 at 14:33 Comment(0)
D
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

Dilan answered 20/2, 2023 at 10:42 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.