Reputation: 14145
I have array of time data in format HH:mm
like 13:58
. Let's say that array has 50 entries with different times. How can I compare new time for example 18:29
is it bigger than any inside array? Should I convert each time into seconds or is there better approach?
Upvotes: 1
Views: 359
Reputation: 48600
You can write a comparator function. All you need to do is pass the hour and minutes into a Date constructor and get the milliseconds.
function toIntArray(arr) {
return arr.map(function(x) { return parseInt(x, 10) });
}
function timeToMillisecondsUTC(time) {
var tokens = toIntArray(time.split(':'));
return Date.UTC(1970, 0, 1, tokens[0], tokens[1]);
}
function timeCompare(a, b) {
return timeToMillisecondsUTC(a) - timeToMillisecondsUTC(b);
}
var dateStrings = [ '13:58', '18:29', '15:25', '12:01' ];
console.log(dateStrings.sort(timeCompare));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Upvotes: 0
Reputation: 2555
Here's a solution that uses regexps and String.replace
to convert the time to a number of minutes, so it can be easily compared.
The uses the Array.every
method to check if every entry of a list returns true from the predicate function
let convert = s => s.replace(/(\d+):(\d+)/, (match, $1, $2) => $1*60 + $2*1);
let list = ["11:25", "10:38"];
let out = list.every(entry => convert(entry) > convert("18:29"));
console.log(out)
Upvotes: 0
Reputation: 1136
You can use momentjs:
var time1 = "18:58";
var time2 = "20:30";
var isBefore = moment(time1, "HH:mm").isBefore(moment(time2, "HH:mm"));
console.log(isBefore);
Upvotes: 1