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
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?
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With