在打字稿中添加小时表

时间:2018-10-03 14:01:19

标签: angular typescript

我正在使用数据表显示记录。这里我有一列显示花费的时间,一行显示总时间(使用函数empPageChange(event)添加所有花费的时间)。这里完美地添加了小时,但分钟像NaN一样显示52:Nan。有人可以帮我解决这个问题

component.ts

empPageChange(event) {
    let list = this.timetables.slice(event.first, event.first + event.rows);
    if (list.length > 0) {
        this.totalHoursSpent = HelperService.addTimes(list, 'HoursSpent');
    } else {
        this.totalHoursSpent = 0;
    }
}

helper.service.ts:

 static addTimes(timeMap, columnName: string) {
    let totalH = 0;
    let totalM = 0;

    // First simply adding all of it together, total hours and total minutes
    for (let x in timeMap) {
        if (x) {
            let timeArray = timeMap[x][columnName].split(':');
            let hour = timeArray[0];
            let minutes = timeArray[1];
            totalH += parseInt(hour, 10);
            totalM += parseInt(minutes, 10);
        }
    }

    // If the minutes exceed 60
    if (totalM >= 60) {
        // Divide minutes by 60 and add result to hours
        totalH += Math.floor(totalM / 60);
        // Add remainder of totalM / 60 to minutes
        totalM = totalM % 60;
    }
    return `${totalH}:${
        totalM.toString().length === 1 ? `0${totalM}` : totalM
        }`;
}

1 个答案:

答案 0 :(得分:1)

由于您使用的是 NaN ,请注意以下几点:

  • 您确定您的 timeArray 仅包含数字吗?也许您可以执行console,log(timeArray[1])进行验证。也许也 TotalM 变量。

  • 您的分钟数是否可能以小数点开头?是否可能是小数点,并且您当前的区域性使用“。”。因为小数点分隔符使它不是数字。

    isNaN(Number("10,5")) //true

    isNaN(Number("10.5")) //false