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