Shambhavi_RB
Shambhavi_RB

Reputation: 121

I want to sort time strings

I have an array of time in string format. For Ex : a = ["10:00 AM", "12:00 AM", "03:00 PM", "01:00 PM"]

I want to sort this string as we sort it in the date format.

I tried moment but couldn't succeed

Upvotes: 0

Views: 37

Answers (2)

Yanick Frehner
Yanick Frehner

Reputation: 21

You can do it like this:

var times = ["10:00 AM", "12:00 AM", "03:00 PM", "01:00 PM"];

times.sort(function (timeA, timeB) {
  return new Date('1970/01/01 ' + timeA) - new Date('1970/01/01 ' + timeB);
});

Upvotes: 1

jSebestyén
jSebestyén

Reputation: 1806

If you want to use moment.js try something like this:

a.sort((firstEl, secondEl) => {
    return moment(firstEl, "HH:MM a").isBefore(moment(secondEl, "HH:MM a"));
}

Upvotes: 0

Related Questions