Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort array with timestamps?

I have an array of timestamps that look like this:

2012-11-19 19:45

I need to sort them by date. I could do a bubble sort or something if i could get the unix timestamp of a date, but i don't know what function gives me that. I looked at strtotime but it won't let me pass a date format. I'm also not sure a bubble sort is the best way to go.

Any suggestions?

Array example:

Also, sorry, i should have mentioned it was in 'show_date'.

Array
(
    [15] => Array
        (
            [show_date] => 2012-11-19 10:40
        )

    [16] => Array
        (
            [show_date] => 2012-11-20 10:40
        )

    [17] => Array
        (
            [show_date] => 2012-11-21 10:40
        )

    [18] => Array
        (
            [show_date] => 2012-11-22 10:40
        )

)
like image 515
qwerty Avatar asked Nov 20 '12 09:11

qwerty


People also ask

How to sort array of objects by timestamp JavaScript?

sort( (objA, objB) => Number(objA. date) - Number(objB. date), ); // 👇️ {id: 3, date: Thu Feb 24 2022, // id: 2, date: Fri Feb 24 2023 // id: 5, date: Wed Feb 24 2027} console. log(sortedAsc); // ✅ Sort in Descending order (high to low) const sortedDesc = arr1.

How do I sort a date in TypeScript?

To sort an array of objects by date in TypeScript: Call the sort() method on the array, passing it a function. The function will be called with 2 objects from the array. Subtract the timestamp of the date in the second object from the timestamp of the date in the first.

Does sort return a new array?

sort() returns the reference to the same array The sort() method returns a reference to the original array, so mutating the returned array will mutate the original array as well.


1 Answers

No need to overcomplicate this. Just use the built-in sort function:

sort($timestamp_array);

You don't need to convert to UNIX timestamps because the strings are in the standard "ISO sortable date" format. That means that if you sort the strings, the dates will be in the correct order.

Here is a php -a session that shows how it works:

php > $ts = array('1986-01-31 12:11', '2012-01-01 13:12', '1980-10-10 12:00');
php > sort($ts);
php > echo var_export($ts);
array (
  0 => '1980-10-10 12:00',
  1 => '1986-01-31 12:11',
  2 => '2012-01-01 13:12',
)
like image 120
Botond Balázs Avatar answered Oct 04 '22 07:10

Botond Balázs