If you came here looking for how to do the opposite, like me, here's what I came up with:
Where newTime
format is "hh:mm a"
, e.g. "12:00 AM"
:
const [timeOnly, period] = newTime.split(' ');
const [hoursStr, minutes] = timeOnly.split(':');
const hoursNum = parseInt(hoursStr);
const hours = period === 'PM' ? ((hoursNum % 12) + 12) % 24 : (hoursNum % 12) % 24;
The only edge case it doesn't handle is if newTime === "0:00 PM"
. Otherwise it works well.
@syntax-junkie 's answer really helped me figure this out!