Given:
- A "base" time in string format 'HH:MM'
- A number of minutes
Create a function that:
- Adds the number of minutes to the "base" time
- Returns the resulting time in 'HH:MM' format
Remember:
- You're working with a standard 12-hour clock
- Hours are one-indexed, not zero-indexed (e.g. there is no
0:40, it's12:40)
addMinutes('01:30', 30); // 2:00
addMinutes('12:30', 40); // 1:10
addMinutes('11:59', 1); // 12:00
addMinutes('01:59', 240); // 5:59
addMinutes('01:23', 456789); // 6:32One valid solution handles hours and minutes separately, and makes use of modular math:
To get total minutes we add the base minute value to the given minutes to add. From there, if we mod (%) by 60 we'll get the remainder, which tells us where the minute hand would end up.
For hours, we already have the total number of minutes, so we can get the total number of hours by dividing that by 60, then the final number of hours by modding (%) by 12.
EDGE CASE: The hours are "one-indexed" not "zero-indexed", i.e. there's no such time as 0:40 (well for non-military clocks), instead it's 12:40. To solve this, we can subtract 1 then mod by 12 then add 1.
function addMinutes (baseTime, minutesToAdd) {
// turn the base time string into an array of 2 numbers
const [baseHours, baseMinutes] = baseTime.split(':').map(str => Number(str));
// convert base time to only minutes & get total minutes
const baseTotalMinutes = (baseHours * 60) + baseMinutes;
const newTotalMinutes = baseTotalMinutes + minutesToAdd;
// Using new total minutes, calculate the hours by dividing by 60
const totalHours = Math.floor(newTotalMinutes / 60);
// This takes care of accounting for a 12 hour clock
// Why do we need to subtract and add 1 here?
const newHours = ((totalHours - 1) % 12) + 1;
// Find minutes by determining how many are left over after dividing by 60
const newMinutes = newTotalMinutes % 60;
// Create return string (account for extra 0 for minutes under 10)
return `${newHours}:${newMinutes > 9 ? newMinutes : `0${newMinutes}`}`;
}