Home > Software engineering >  Find time difference between 2 dates with days, hours and minutes
Find time difference between 2 dates with days, hours and minutes

Time:11-02

Let's suppose I have a array list with all these following data.

let events = {
      ["-1 19:00"],
      ["-1 20:00"],
      ["-1 17:00", "-1 23:00"],
      ["1 18:00"],
      ["2 18:00"],
      ["3 18:00"],
      ["4 18:00"],
      ["5 18:00"],
      ["6 18:00"],
      ["7 18:00"],
    };

So, Here -1 represents every single day, Like every "sunday, monday" and so on. -1 = everyday, 1 = Monday, 2 = Tuesday and so on.

So, I want to calculate The time left from the current time to the nearest day with hours and mins inside the array. I'm really lacking idea on how I'm supposed to do it.

getTimeLeftTillDay(dayname, time) :any {
        let d = new Date();
        let comming = parseInt(dayname);
        if(comming === -1) {
          comming = d.getDay();
        }
        const day = d.getDay();
        const targetDay = comming;  // Someday
        let dayOffset = targetDay - day;
        if (dayOffset < 0) dayOffset  = 7;
        d = new Date(d.getTime()   (dayOffset * 24 * 3600 * 1000));
        let timea = parseInt(time[0]);
        let timeb = parseInt(time[1]);
        d.setHours(timea);
        d.setMinutes(timeb);
        return d;
}

I tried to use the above code but it doesn't work as I expected. I'll really like help!

CodePudding user response:

If relying on a 3rd-party library is ok for you, I'd use one of the many date-libs to perform the calculations. Here's how you could do it using date-fns:

import {addDays, formatDuration, intervalToDuration, setHours, setMinutes} from "date-fns";

const getTimeLeftTillDay = (dayName, time) => {
    let daysToAdd = 0;
    if (dayName !== '-1') {
        daysToAdd = Number.parseInt(dayName);
    }
    const startDate = new Date();
    let endDate = addDays(startDate, daysToAdd);

    const [minutes, seconds] = time.split(":");
    const hoursToSet = Number.parseInt(minutes);
    endDate = setHours(endDate, hoursToSet)
    const minutesToSet = Number.parseInt(seconds);
    endDate = setMinutes(endDate, minutesToSet)
    return customFormatDuration(startDate, endDate);
}

export const customFormatDuration = (start, end) => {
    const durations = intervalToDuration({start, end})
    return formatDuration(durations);
}

console.log(getTimeLeftTillDay("-1", "19:00"));
console.log(getTimeLeftTillDay("1", "02:00"));
console.log(getTimeLeftTillDay("7", "02:00"));

This prints the following on my machine (executed at 2:25 pm, CET):

4 hours 35 minutes
11 hours 35 minutes
6 days 21 hours 35 minutes
  • Related