Difference between two time using dayjs
Asked Answered
M

4

9

I have two inputs of time and I want to get the difference/time-interval between these two using dayjs

fromtime = '13:00'
totime = '17:00'

So the output for the above two should be 4:00 hours

I tried

console.log(
          dayjs(fromtime).diff(dayjs(totime), "hours")
        );

But am not getting the expected output.

Mufti answered 14/2, 2020 at 12:9 Comment(2)
What is the error you are getting? Maybe you should not pass them as strings.Hoopla
Nan is what I'm getting in the outputMufti
M
10

I found the solution to this.

const fromtime = '11:20'
const totime = '12:30'

const ft = dayjs(`2000-01-01 ${fromtime}`);
const tt = dayjs(`2000-01-01 ${totime}`);
const mins = tt.diff(ft, "minutes", true);
const totalHours = parseInt(mins / 60);
const totalMins = dayjs().minute(mins).$m

This will give the output as totalHours = 1 and totalMins = 10.
Hope this help someone.

Mufti answered 28/7, 2020 at 0:55 Comment(1)
you can set param 'hours'Aspirant
T
4

Dayjs expects a Date in a certain format (dayjs parse string) not just a time. However you can set the hour (dayjs set hour) without setting a certain date (dayjs parse now):

var fromtime = dayjs().hour(13)
var totime = dayjs().hour(17)

console.log(totime.diff(fromtime, "hours"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>

EDIT

What if the input contains fromtime = '10.25' and totime = '11.30'. So my output should be '1.05'. But when I follow your method the output is 1. Is there a way to solve this

You can set The minutes also (dayjs set minute). Unfortunately i do not see any formatting options for time-differences in that library. So we will have to calculate that on our own:

function formatInterval(minutes) {
  let interval = [
    Math.floor(minutes / 60).toString(),  //hours ("1" - "12")
    (minutes % 60).toString()             //minutes ("1" - "59")
  ];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

let fromtime = dayjs().hour(10).minute(25);
let totime = dayjs().hour(11).minute(30);

let interval = totime.diff(fromtime, "minute");

console.log(formatInterval(interval));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>

EDIT2

This will fail if the day switches between the two first lines

OK was assuming the fromtime will always be a smaller number than the totime ... if thats not the case we can just substract negative amount of minutes from the total amount of minutes in a day like so:

function formatInterval(minutes) {
  let interval = [Math.floor(minutes / 60).toString(), (minutes % 60).toString()];
  return interval[0].padStart(2, '0') + ':' + interval[1].padStart(2, '0')
}

function getInterval(from, to) {
    let [hoursA, minutesA] = from.split(':');
    let [hoursB, minutesB] = to.split(':');
    let timeA = dayjs().hour(hoursA).minute(minutesA);
    let timeB = dayjs().hour(hoursB).minute(minutesB);
    let interval = timeB.diff(timeA, 'minutes');
    if(interval < 0) {
      return formatInterval(24 * 60 + timeB.diff(timeA, 'minutes'));      
    }
    return formatInterval(interval);
}

console.log(getInterval('23:00', '1:45'));
console.log(getInterval('10:25', '11:30'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/dayjs/1.8.20/dayjs.min.js"></script>
Toponym answered 14/2, 2020 at 12:23 Comment(2)
What if the input contains fromtime = '10.25' and totime = '11.30'. So my output should be '1.05'. But when I follow your method the output is 1. Is there a way to solve thisMufti
This will fail if the day switches between the two first linesIndignant
L
0
fromtime = '13:00'
totime = '17:00'

These are currently strings and you need to convert it into integers.

console.log(parseInt(fromtime) - parseInt(totime)) //4
Lymphocytosis answered 5/8, 2020 at 7:1 Comment(0)
A
0
// Addition, Difference between two time zones
    
import timezone from 'dayjs/plugin/timezone';
dayjs.extend(timezone);
                
const d1 = dayjs((dayjs().tz('Europe/Kiev').format('YYYY-MM-DDTHH:mm')));
const d2 = dayjs((dayjs().tz('Europe/London').format('YYYY-MM-DDTHH:mm')));
                
console.log(d1.diff(d2, 'hours', true)); // 2
Aspirant answered 1/1, 2023 at 22:20 Comment(0)

© 2022 - 2025 — McMap. All rights reserved.