I'm writing javascript code from scratch that should add time to current time. I have declared three variables: h - hours, min - minutes, truk - duration (minutes).
let h = +prompt("Enter current hour: ");
let min = +prompt("Enter current minutes: ");
let truk = +prompt("Enter duration (minutes): ");
let min1 = truk % 60; // We get minutes from duration
let h1 = Math.trunc(truk / 60); // We get hours from duration
console.log("You have entered: " + "h = " + h + ", " + "min = " + min + ", " + "truk = " + truk);
console.log("Result: " + (h + h1) + " : " + (min + min1)); // Don't know how to proceed further with this.
For example if we enter hours 17 and minutes 35 and duration 20 it should print out 17:55
let h = +prompt("Enter current hour: ");
let min = +prompt("Enter current minutes: ");
let truk = +prompt("Enter duration (minutes): ");
let min1 = truk % 60; // We get minutes from duration
let h1 = Math.trunc(truk / 60); // We get hours from duration
console.log("You have entered: " + "h = " + h + ", " + "min = " + min + ", " + "truk = " + truk);
//without if
var result1 = new Date(2021, 0, 1, h, min, 00, 000); //set time according to user inputs
result1.setMinutes(result1.getMinutes() + truk); //add minutes to set time
console.log("Result: " + (result1.getHours()) + " : " + (result1.getMinutes()));
you need to check if minutes are going over 60. If yes then add an hour to existing hrs. Same logic must be applied if hrs are going beyond 24. Try this :
let h = +prompt("Enter current hour: ");
let min = +prompt("Enter current minutes: ");
let truk = +prompt("Enter duration (minutes): ");
let min1 = truk % 60; // We get minutes from duration
let h1 = Math.trunc(truk / 60); // We get hours from duration
console.log("You have entered: " + "h = " + h + ", " + "min = " + min + ", " + "truk = " + truk);
let min_final = 0
let hr_final = h
if((min + min1) > 60){
min_final = (min + min1) - 60
hr_final = hr_final + 1
}
hr_final = hr_final + h1
if(hr_final >= 24){
hr_final = 24 - hr_final
}
if(hr_final < 10){
hr_final = "0" + hr_final
}
console.log("Result: " + (hr_final) + " : " + (min_final));
You're on the right track, but you need to consider some additional factors:
% again to ensure that the values you return back are base-24 (for hours) and base-60 (for minutes).10 at 17:55 should return 18:05, not 17:05).10 - a bit of string manipulation with String.substr() can go a long way in this scenario.let h = +prompt("Enter current hour: ");
let min = +prompt("Enter current minutes: ");
let truk = +prompt("Enter duration (minutes): ");
let newMin = ('0' + (min + (truk % 60)) % 60).substr(-2);
let newH = (h + Math.trunc((truk + min) / 60) + Math.trunc(truk / 60)) % 24;
console.log("You have entered: " + "h = " + h + ", " + "min = " + min + ", " + "truk = " + truk);
console.log("Result: " + newH + " : " + newMin);