-1

I have a json objects that have a time key and value, for example:

[
    {
        "name" : "Meeting 1",
        "time" : "9:30am",
        "day" : "Sunday",
        "location" : "Summit",
    },
    {
        "name" : "Meeting 2",
        "time" : "10:00am",
        "day" : "Sunday",
        "location" : "Juab",
    }
]

What I would like the do is sort them by the time property, but you can see the dilemma. If I use Angular's orderBy method it will say 10:00am should come before 9:00 am. I thought about splitting up the objects into am and pm, but still end up with the same problem.

I am brand new to Angular, so I don't know the best way to solve this. Any ideas?

pizzarob
  • 11,711
  • 6
  • 48
  • 69
  • 2
    You either write a custom filter that is smart enough to sort the way you want, or you try to leverage functionality out of existing libraries such as moment.js ... either way, looks like you need a custom filter – link64 Aug 11 '14 at 02:24
  • Without a date, who's to say that 9:00 comes before 10:00? It could be that 10:00 on day 1 comes before 9:00 on day 2. Consider companies that operate 24x7. An 11:00PM meeting could be well before a 2:00AM meeting. – Matt Johnson-Pint Aug 11 '14 at 02:26
  • @MattJohnson you're right. The example above is for example purposes only. The objects actually have day properties and I filter them by days of the week. – pizzarob Aug 11 '14 at 02:33
  • Please show example real values that you're actually working with. Else the answer will be quite different. – Matt Johnson-Pint Aug 11 '14 at 02:44

1 Answers1

2

The easiest thing to do is to convert your 12 hour (AM/PM) to 24 hour time integer.

For example (from: convert 12-hour hh:mm AM/PM to 24-hour hh:mm):

function convertTo24Hour(time) {
    var hours = parseInt(time.substr(0, 2));
    if(time.indexOf('am') != -1 && hours == 12) {
        time = time.replace('12', '0');
    }
    if(time.indexOf('pm')  != -1 && hours < 12) {
        time = time.replace(hours, (hours + 12));
    }
    time = time.replace(':','').trim();
    return parseInt(time.replace(/(am|pm)/, ''));
}

Thus 1:00pm is now 1300 and 2:00pm is 1400pm etc... That way you can sort correctly without the cost of more complex date functions.

You can convert back for display or create a third property for your object as time_24.

This is not a complete soultion but a starting point. For more details, see Descending order by date filter in AngularJs

Community
  • 1
  • 1
Todd Moses
  • 10,969
  • 10
  • 47
  • 65