Military time conversion functions

2021 May 1st

These are JavaScript functions I made for converting military-time to minutes, and vice versa.

1function militaryToMinutes(string) {
2 let h = Number(string.match(/[^:]+/)); //match first 1 or 2 numbers
3 let m = Number(string.match(/(?<=:)../)); //match last 2 numbers
4 return h * 60 + m;
5}
6
7function minutesToMilitary(num) {
8 let h = Math.floor(num / 60);
9 let m = num % 60;
10 if (m < 10) {
11 //if a zero is needed for military time
12 let f = "0";
13 m = f + `${m}`;
14 }
15 return `${h}:${m}`;
16}
17
18militaryToMinutes("10:00"); //600
19
20minutesToMilitary(600); //'10:00'