How to sort an array of dates

Hey everyone, a bit stuck with trying to put an array of dates into chronological order that I have retrieved from the database, and then reformat them. Sorting them into chronological order is no problem.

	$result = $conn->query($sql);

if ($result->num_rows > 0) {
	while($row = $result->fetch_assoc()) {
		$dateReserved[] = $row['date'].'<br />';

<?php  } // while
} //  num rows

foreach ($dateReserved as $value) {
	//echo $value;
	echo date('D, j M Y', strtotime($value));


But, as soon as I try to reformat it by uncommenting this line :

echo date('D, j M Y', strtotime($value));

I just get back ‘Thu, 1 Jan 1970’.

It doesn’t like it if I try to reformat it. Does anyone know what I am doing wrong and can you perhaps provide a code example?

If your dates are in the form YYYY-MM-DD, they will sort alphanumerically correctly with a standard sort - because you compare strings left to right, so it will compare the year first, then the month, then the day. (note that it’s important to get two-digits for month and day in this case.)

Alternatively, use your query to sort the results, and your walk through the result will be in order also.

… and eventually i’ll read the WHOLE post. Shhhhh…

If you get back 1 Jan 1970, it means whatever went into strtotime wasnt a valid date format. (timestamp 0 is 00:00:00 1 Jan 1970)

What is the value of $value? Echo it out.

Your code is concatenating a <br /> tag on the end of the dates it is storing into the array. Why is it doing that?


Which is why strtotime isn’t working…


So why don’t you let the database sort this?


This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.