Struggling with formatting time formats received from a database? Looking to convert two types of data from the database into a visually appealing format on your page? For example, database value 400 should be displayed as 04:00 and 1830 as 18:30. Here's the code I'm using:
formatTime(time) {
//Ensure at least three characters
if (time.length > 2) {
let firstDigits = time.substring(0, time.length - 2);
let lastDigits = time.slice(-2);
let formattedHour = (firstDigits.length > 1) ? firstDigits + ":" + lastDigits : "0" + firstDigits + ":" + lastDigits;
return formattedHour;
} else if (time.length <= 2) {
let firstDigits = '00';
let lastDigits = time;
let formattedHour = (lastDigits.length < 2) ? firstDigits + ":0" + lastDigits : firstDigits + ":" + lastDigits;
return formattedHour;
}
return time;
}
Expecting 400 to display as 04:00, 1830 as 18:30, but encountering issues. Any assistance would be greatly appreciated.