Search code examples
javascriptdatedatetimedayjs

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


Solution

    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?