JSFiddle - React, Tailwind, and code Playground
by Florian Bar
JavaScript
const formatTime = (value) => {
let time = "";
if (value) {
let date = new Date(value);
// regex for matching a time string
const isValidTime = /([0-1]?[0-9]|2[0-4]):([0-5][0-9])(:[0-5][0-9])?(\s?(AM|PM))?$/i.test(
value
);
console.log(!isNaN(date.getTime()));
// we can't parse this, lets return
if (isNaN(date.getTime()) && !isValidTime) return "";
if (!isNaN(date.getTime())) value = date.getTime();
console.log(date);
// if date is invalid but the string is a valid time string
// lets manually set the time on a fresh date object
if (!isNaN(date.getTime()) || isValidTime) {
// remove AM and PM strings from time if there are any
const timeOnly = value
.split(/\s/)[0]
.toLowerCase()
.replace("am", "")
.replace("pm", "");
date = new Date();
// converting 12 hour to 24 hour if needed
const hours =
value.toLowerCase().includes("pm") && timeOnly.split(":")[0] < 12
? parseInt(timeOnly.split(":")[0]) + 12
: timeOnly.split(":")[0];
date.setHours(hours);
date.setMinutes(timeOnly.split(":")[1]);
}
time = date.toLocaleTimeString(undefined, RESPONSE_DATE_FORMAT.TIME);
}
return time;
};
console.log(formatTime(new Date("2021-03-05T07:50:37.455Z")));
console.log(formatTime("11:00"));
//console.log(formatTime("01:60"));
//console.log(formatTime("1:01:60"));