为什么会发生?带有JavaScript(带有Date()减法)的奇怪行为。 CodePen +视频

时间:2019-03-01 22:26:02

标签: javascript jquery

我是JavaScript的新手,我正在构建一个简单的应用来计算我的工作时间。

当我减去两个日期时,它可以正常工作(例如,结果为1:30),但是当我添加第三个日期时,这是一种奇怪的行为,其结果是 +1个添加小时,而分钟是 59 44 29 14 (始终为-1分钟,而第三个日期本身始终为0,15, 30.45分钟)。我假设 +1添加小时是-1,但是它是通过 Date()转换为绝对数字的。

问题的视频链接: https://youtu.be/EyhaVgwxOpw

CodePen:https://codepen.io/anon/pen/PLNqMa

代码

 var startHr,
    startMin,
    endHr,
    endMin,
    pause;

$(".start,.end,.pochivka").change(function () {
     startHr = Number($('#starthr').children("option:selected").val());
     startMin = Number($('#startmin').children("option:selected").val());
     endHr = Number($('#endhr').children("option:selected").val());
     endMin = Number($('#endmin').children("option:selected").val());
     pause = Number($('#pause').children("option:selected").val());

});
$(".calculate").click(function(){

    // Refer to starting hours and ending hours which get their value from chosen fields
    var secondTime = startHr + ":" + startMin +":00";
    var firstTime = endHr + ":" + endMin + ":00";
    // breakTime also gets from the same place, but has strange behaviour
    var breakTime = "00:" + pause + ":00";
    console.log(breakTime);

    let startHour = new Date().setHours(...(firstTime.split(":")));
    let endHour = new Date().setHours(...(secondTime.split(":")));
    let removeBreakHours = new Date().setHours(...(breakTime.split(":")));

    // Disable next line (and enable the code with next comments)
    // to see how normal it works without the bug 
    // Maybe it happens because I have 2 subtractions?
    let finalHours = new Date(startHour - endHour - removeBreakHours);

    // Now enable next line.It is the code without "Break times remove"
    // let finalHours = new Date(startHour - endHour);

    // ------------ 
    var workedHours = finalHours.getUTCHours() +":"+ finalHours.getUTCMinutes();
    $('.workHours').text(workedHours);

})

1 个答案:

答案 0 :(得分:0)

我通过将休息时间添加为负分钟来使其正常工作

$(".calculate").click(function(){

    // Refer to starting hours and ending hours which get their value from chosen fields
    var secondTime = startHr + ":" + startMin +":00";
    var firstTime = endHr + ":" + endMin + ":00";

    let startHour = new Date().setUTCHours(...(firstTime.split(":")));
    let endHour = new Date().setUTCHours(...(secondTime.split(":")));

    let finalHours = new Date(startHour - endHour);
    finalHours.setMinutes(- +pause);

    // ------------ 
    var workedHours = finalHours.getUTCHours() +":"+ finalHours.getUTCMinutes();
    $('.workHours').text(workedHours);
})

在您的示例中,您减去了毫秒(准确地说是自UTC 1970年1月1日以来经过的毫秒),所以我想当JS舍入时,结果舍入为较低的值,导致比预期少1分钟。但是我还没有证明。