I am new with JavaScript and I am building a simple app to calculate my worked hours at work.
When I am subtracting two dates - it works fine (the result is 1:30, for example), but as soon as I add the third date it has a strange behavior and the result is +1 added hour and minutes are 59 44 29 14 (always -1 minute , while the third date itself is always a 0,15,30,45 minutes). I assume the +1 added hour is -1,but it was converted to an absolute number by Date().
Video link to the problem : https://youtu.be/EyhaVgwxOpw
CodePen : https://codepen.io/anon/pen/PLNqMa
Code
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);
})