Skip to content

Instantly share code, notes, and snippets.

@chrdek
Created October 12, 2020 17:54
Show Gist options
  • Save chrdek/50e2b6e5bf8a7d3febc4595ee1142994 to your computer and use it in GitHub Desktop.
Save chrdek/50e2b6e5bf8a7d3febc4595ee1142994 to your computer and use it in GitHub Desktop.
Time Converter function (12Hr-24Hr format) using Javascript
// This oneliner function converts 12-Hour time into its 24-Hour counterpart.
// Examples (hh:mm:ss(PM/AM) to HH:MM:ss(24hour):
// 12:00PM ->12:00, 12:00AM->00:00, 04:00PM -> 16:00
function timeConversion(s) {
return (s.includes("PM")) ?
(s.replace(s.split(':')[0],(s.startsWith("12"))?s.split(':')[0]:(Number(s.split(':')[0])+12)+"")).replace("PM","") :
(s.replace(s.split(':')[0],
(s.startsWith("12"))?(s.split(':')[-1])||"00":s.split(':')[0])
.replace(s.split(':')[0],
(( (s.split(':')[0]).length==1 )&&( (!s.split(':')[0]).startsWith("0") ))?(s.split(':')[-1])||"0"+(s.split(':')[0]):s.split(':')[0]
)).replace("AM","");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment