简体   繁体   English

获取两个变量之间的差异

[英]Get the difference between two variables

I have an object and Hours is saved as a string.我有一个 object 和 Hours 保存为字符串。 I need to convert the string to hours and then get the difference between the 2 variables.我需要将字符串转换为小时,然后得到 2 个变量之间的差异。

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)将字符串转换为小时 (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.基本问题是您正在gSchedule.hourTogSchedule.hourFrom并在它们是字符串值时尝试使用它们执行算术运算。 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.在这种情况下,相关的数字部分是HH:MM字符串的小时部分,因此使用带有:作为分隔符的拆分 function 将返回两个字符串的列表,一个小时字符串和一个分钟字符串。 We can then parse the hours string to get an int, float, or other numeric type.然后我们可以解析小时字符串以获取 int、float 或其他数字类型。

//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.如果您想进一步阅读您在此处获得的答案之外的不同方法, 这是一个类似的问题,可能对参考有用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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