I have an object that looks like this:
JavaScript
x
2
1
["09:00 AM", "12:00 PM", "03:00 PM"]
2
I want to simply take these values and parse them into a integer between 0-24 basically, currently I’m taking it in like this:
JavaScript
1
2
1
if ("09:30 AM") { return 9.5}
2
Is there a better way to do this?
Advertisement
Answer
This solution maps the time format input to a number between 0 (inclusive) to 24 (exclusive), just like the 24-hours format.
JavaScript
1
12
12
1
function parse(dfmt) {
2
const [hh, mmdp] = dfmt.split(":")
3
const [mm, dp] = mmdp.split(" ")
4
5
const hours = parseInt(hh)
6
const minutes = parseInt(mm)
7
8
return (dp == "AM" ? 0 : 12) + (hours % 12) + (minutes / 60)
9
}
10
11
const dfmts = ["09:00 AM", "03:00 PM", "09:30 PM", "12:00 AM", "12:00 PM"]
12
dfmts.forEach(dfmt => console.log(parse(dfmt)))