How to orderBy collections using AM/PM in Laravel

Avatar
C

Callum Davies

Senior Backend Engineer••
7352Views
5mRead
0Reactions

To sort a collection of data in Laravel by a string that represents AM/PM time, you can use the sortBy method and a custom sorting function. Here's an example:

$times = collect(["10:00 PM", "9:00 AM", "12:00 PM", "1:00 AM"]);



$sortedTimes = $times->sortBy(function ($time) {

    $parts = explode(" ", $time);

    $hour = intval($parts[0]);

    $minute = intval(explode(":", $parts[0])[1]);

    $ampm = $parts[1];



    if ($ampm === "PM") {

        $hour += 12;

    }



    return sprintf("%02d:%02d", $hour, $minute);

});



return $sortedTimes;

This will return a sorted collection of times, such as:

 

["1:00 AM", "9:00 AM", "12:00 PM", "10:00 PM"]

Connect with KoderSolution 🚀

Master modern software engineering, scalable architectures, and advanced backend systems.

What's your setup?How does your production stack handle background jobs? Are you using Redis with Horizon, or cloud queues like AWS SQS?
Callum Davies
C
Written by•Senior Backend Engineer

Callum Davies

PHP & Laravel practitioner since v5.4. Big believer in thin controllers, explicit return types, and boring modular architecture that doesn't page you on weekends.

React to this article

Recommended Articles

View all articles