hello guys i need to format time to values like this:
00:00 ==> 0
00:15 ==> 0.25
00:30 ==> 0.5
00:45 ==> 0.75
....
16:00 ==> 16
16:15 => 16.25
16:30 => 16.5
16:45 => 16.75
i already used switch case:
switch (time) {
case "00:00":
return { value: 0, time: time };
case "00:30":
return { value: 0.5, time: time };
case "01:00":
return { value: 1, time: time };
case "01:30":
return { value: 1.5, time: time };
case "02:00":
return { value: 2, time: time };
case "02:30":
return { value: 2.5, time: time };
case "03:00":
return { value: 3, time: time };
....
but i think its not optimized any better idea?
You could divide the minutes by the hour length.
const
formatTime = s => +s.split(':').map((d, i) => i ? d / 0.6 : d).join('.');
console.log(formatTime('00:45'));
console.log(formatTime('01:15'));
You could use replace callback, replacing all except an initial zero, then format the two components to a decimal number and format with 2 decimals (using toFixed). This works for all minutes (from 0 to 59).
Demo:
const formatTime = s => s.replace(/([1-9]\d?):(.+)/, (_, m, s) => (+m+s/60).toFixed(2));
// Demo
for (let min = 0; min < 40; min++) {
const time = '09:' + (min < 10 ? "0" + min : min);
console.log(time, "=>", formatTime(time));
}