Last active
November 19, 2021 16:41
-
-
Save shivpatel/119015b5b76d4954f3183c351450f751 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function parse(str) { | |
let tmp = str.trim().toUpperCase() | |
tmp = tmp.replaceAll(" ", "") | |
tmp = tmp.replaceAll(":", "") | |
let matches = tmp.match(/([0-9]{1,4})(AM|PM)/g) | |
if (matches.length === 0) { | |
return | |
} | |
let match = matches[0].split('') | |
// match= 3PM, 30PM, 300PM, 3000PM | |
let timeOfDay = match.splice(-2).join('') // AM or PM | |
// match= 3, 30, 300, 3000 | |
let hr | |
let min | |
switch(match.length) { | |
case 1: | |
case 2: | |
hr = match.join('') | |
min = "00" | |
break; | |
case 3: | |
hr = match.slice(0, 1).join('') | |
min = match.slice(1, 3).join('') | |
break | |
case 4: | |
hr = match.slice(0, 2).join('') | |
min = match.slice(2, 4).join('') | |
break | |
} | |
if (hr >= 1 && hr <= 12 && min >= 0 && min <= 59) { | |
return `${hr}:${min} ${timeOfDay}` | |
} | |
} | |
console.log('3pm', parse('3pm')) | |
console.log('12pm', parse('12pm')) | |
console.log('13pm', parse('13pm')) | |
console.log('315am', parse('315am')) | |
console.log('1215am', parse('1215am')) | |
console.log('11:45am', parse('11:45am')) | |
console.log('3015am', parse('3015am')) | |
console.log('jk2j4pm', parse('jk2j4pm')) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment