JSFiddle - React, Tailwind, and code Playground
by chauhangs
JavaScript
function tConvert(stime, etime) {
var i = 0;
var j = 0;
// Check correct time format and split into components
stime = stime.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [stime];
if (stime.length > 1) { // If time format correct
stime = stime.slice(1); // Remove full string match value
i = stime[0];
stime[3] = +stime[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
stime[0] = +stime[0] % 12 || 12; // Adjust hours
}
var strt = stime.join(''); // return adjusted time or original string
console.log(strt);
// Check correct time format and split into components
etime = etime.toString().match(/^([01]\d|2[0-3])(:)([0-5]\d)(:[0-5]\d)?$/) || [etime];
if (etime.length > 1) { // If time format correct
etime = etime.slice(1); // Remove full string match value
j = etime[0];
etime[3] = +etime[0] < 12 ? ' AM' : ' PM'; // Set AM/PM
etime[0] = +etime[0] % 12 || 12; // Adjust hours
}
var end = etime.join(''); // return adjusted time or original string
console.log(end);
}
tConvert('09:00:00', '18:00:00')