Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

257
Views
Take time values into integer?

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?

about 4 years ago · Juan Pablo Isaza
3 answers
Answer question

0

You can create a methods to convert time to float number and then use map to call function on each item of your array. Now you have array of float numbers:

Here is working snippet:

function timeStringToFloat(time) {
            var hoursMinutes = time.split(/[.:]/);
            var hours = parseInt(hoursMinutes[0], 10);
            var minutes = hoursMinutes[1] ? parseInt(hoursMinutes[1], 10) : 0;
            return hours + minutes / 60;
}

var data = ["09:30 AM", "12:00 PM", "03:00 PM"]

var d = data.map(t => timeStringToFloat(t))

console.log(d);

about 4 years ago · Juan Pablo Isaza Report

0

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)))

about 4 years ago · Juan Pablo Isaza Report

0

This should work. It parses "12:00 PM" to 12.0 and "12:00 AM" to 0.0:

const times = ["09:30 AM", "01:24 AM", "03:00 PM", "12:00 AM", "12:00 PM"]

function time2Float(a) {
  return a.map(t => {
    const apm = t.split(" ")[1];
    let h = parseInt(t.split(":")[0]);
    let m = parseInt(t.split(" ")[0].split(":")[1]);
    
    apm === "PM" && h !== 12 && (h += 12);
    apm === "AM" && h === 12 && (h -= 12);
    m = (m * 100) / 60;
    return parseFloat(h + "." + m);
  });
}

console.log(time2Float(times));

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!