Sort Time: 12-hour Format

I’m having a problem sorting pages by time. It seems like there’s confusion because they’re in a 12-hour format. For example, pages that have a start time of 11:00am are displaying after pages with a start time of 9:00pm. Here’s the code I’m using so far in my snippet:

<?php $saturday = page('program')->children()->filterBy('date', strtotime('2018-11-17')); ?>

  <?php foreach($saturday->sortBy('start', 'asc') as $event): ?>
      <time><?php echo $event->start() ?> — <?php echo $event->end() ?></time>
  <?php endforeach ?>

Any idea what the problem is? Is there a way I could convert to a different format for sorting, while still displaying the time as a 12-hour value in my list?

You can use the map() method to create a virtual 24-hour format field and then sort by this field, while you still output your original startfield:

$events = $saturday->map(function($child) {
  $child->start24 = $child->date('H:i', 'start');
  return $child;
})->sortBy('start24', 'asc');

foreach($events as $event) {
  echo $event->start();

Yes! That’s exactly what I was looking to do. Thanks for your help.


Sorry for my late answer.
Since this problem does not occur when I use the Kirby panel to enter the date or datetime field, I suspect that you do your input without using the Kirby panel and/or you save your data “not without format”.

Separating form and content avoids your problem; the field would then be e.g. saved in the format “YYYY-MM-DD” or “YYYY-MM-DD H:i” (and the pages can be sorted in this format).
You can then also freely choose the form of time representation in the panel; this logically has no effect on the storage format.
In the code of the template or its snippets the formatting would be like you want, e.g. with “a.m.” or “p.m.” respectively. That may depend on the language of the user interface, but never on the format of the saved data.

As an example of the separation of form and content, you can use the Kirky langkit, which shows two languages and their different time formats.