获取两个变量之间的差

时间:2019-10-22 17:54:45

标签: javascript node.js typescript

我有一个对象,并将Hours保存为字符串。我需要将字符串转换为小时,然后获取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;
}

将字符串转换为小时(NAN)的问题

2 个答案:

答案 0 :(得分:0)

我试图用一种非常冗长的方式写东西。您可以执行以下操作:

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;

答案 1 :(得分:-1)

基本问题是,当gSchedule.hourTogSchedule.hourFrom是字符串值时,您要对其进行算术运算。您需要分割字符串并提取数字类型以执行这种类型的数学计算。

在这种情况下,相关的数字部分是HH:MM字符串的小时部分,因此使用以:作为分隔符的split函数将返回两个字符串,一个小时字符串和一个字符串的列表。一分钟。然后,我们可以解析小时字符串以获取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)

如果您想进一步了解除此处给出的答案以外的其他方法,请this is a similar question that may be useful to reference.