Skip to content
Advertisement

Take time values into integer? [closed]

I have an object that looks like this:

["09:00 AM", "12:00 PM", "03:00 PM"]

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:

if ("09:30 AM") { return 9.5}

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.

function parse(dfmt) {
  const [hh, mmdp] = dfmt.split(":")
  const [mm, dp] = mmdp.split(" ")

  const hours = parseInt(hh)
  const minutes = parseInt(mm)

  return (dp == "AM" ? 0 : 12) + (hours % 12) + (minutes / 60)
}

const dfmts = ["09:00 AM", "03:00 PM", "09:30 PM", "12:00 AM", "12:00 PM"]
dfmts.forEach(dfmt => console.log(parse(dfmt)))
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement