简体   繁体   中英

Get the difference between two variables

I have an object and Hours is saved as a string. I need to convert the string to hours and then get the difference between the 2 variables.

const groupSchedule=[
    {"days":"sat","Hourfrom":"15:00","Hourto":"19:00"},
    {"days":"sun","Hourfrom":"15:00","Hourto":"19:00"},
    {"days":"mon","Hourfrom":"15:00","Hourto":"19:00"},
]
function numberOfHoursInWeek(groupSchedule) {
    let hours = 0;
    for (const gSchedule of groupSchedule) {
           let hour = gSchedule.Hourto.to - gSchedule.Hourfrom;
        console.log(hour);
        hours += hour;
    }
    return hours;
}

Problem in converting string to hour (NAN)

I tried to write in a very verbose way. You could do something like this:

const hoursTo = "19:33";
const hoursFrom = "14:55";
const hoursToArray = hoursTo.split(":");
const hoursFromArray = hoursFrom.split(":");
const hoursToDate = new Date(0, 0, 0, hoursToArray[0], hoursToArray[1], 0, 0); 
const hoursFromDate = new Date(0, 0, 0, hoursFromArray[0], hoursFromArray[1], 0, 0); 
const difference = Math.abs(hoursToDate - hoursFromDate) / 36e5;
console.log(hours) //4.633333333333334;

The basic issue is that you are taking gSchedule.hourTo and gSchedule.hourFrom and trying to perform arithmetic with them when they are string values. You need to split the string and extract a numeric type to perform this type of mathematical calculation.

In this case the relevant numeric portion is the hours portion of the HH:MM string, so using the split function with : as a delimiter will return a list of two string, one string of hours and one of minutes. We can then parse the hours string to get an int, float, or other numeric type.

//split time strings on the ':'
let hrToSplit = gSchedule.hourTo.split(':')
let hrFromSplit = gSchedule.hourFrom.split(':')

//parse time strings to extract hour as int
let hrToNum = parseInt(hrToSplit[0], 10)
let hrFromNum = parseInt(hrFromSplit[0], 10)

//perform whatever math is needing using the numbers themselves, not the strings
console.log(hrToNum + hrFromNum)

If you want to do some further reading on different approaches beyond the answers you got here, this is a similar question that may be useful to reference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM