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
)
)
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.
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.
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.
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',
)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With