0

I'm making a news feed which stores dates as a string like Tuesday 05 June 2012 04:14:44 PM.

I want to do two things.

  1. Sort the news feed by date (newest to oldest)
  2. If the date is today's date, show only the time(which is also sorted).
3
  • 2
    which stores dates as a string what on earth makes people to do so? no, i'm realy interested, cause i can find no reason. Commented Jun 5, 2012 at 7:19
  • I had it sorted by date, but I couldn't figure out how to sort the time as well, at least not without a lot of embedded if and while statements etc. Commented Jun 5, 2012 at 7:24
  • 1
    You can store the news by id, or use strtotime(), you'll get numbers, the higher the numbers, the recent it is, you can also then convert it to string with the date() function, google is your friend :) Commented Jun 5, 2012 at 7:30

3 Answers 3

3

I would change the storage to store some "unix timestamp". From that you can print out whatever format of date you like. And also, it's a number and is very easily sortable.

Sign up to request clarification or add additional context in comments.

Comments

0

I guess this will work for your problem, yet i advise you to modify your table design if possible.

$result = mysql_query("SELECT * FROM newsfeed");

$records = array();
$i = 0;
while ($row = mysql_fetch_array($result))
{
    $records[$i] = array('news_idPK' => $row['news_idPK'],
                     'date' => date("Y-m-d H:i:s", strtotime($row['date'])),
                     'news' => $row['news']
    );
    $i++;
}
usort($records, "cmp");

function cmp($a, $b) {
    $a = strtotime($a['date']);
    $b = strtotime($b['date']);
    return $a - $b;
}

$ctr = count($records)-1;
for($x=$ctr; $x>=0; $x--)
{
    $newsDate = date("l d F Y h:i:s A", strtotime($records[$x]['date']));
    if(date("Y-m-d", strtotime($records[$x]['date'])) == date("Y-m-d"))
    {
        $newsDate = date("h:i:s A",strtotime($records[$x]['date']));
    }
    echo $records[$x]['news_idPK']." - ".$newsDate." - ".$records[$x]['news']." <br/>";
}

2 Comments

.:oh yeah, sorry bout that.tnx! :)
-2

This sorting method isn't effective. You can add an ID column and sort by ID. each time someone post a post , and it's inserted to the feed - a incremented ID will be inserted. it's parallel to date sorting - you want the newest.

it's the most recommended and effective sorting method.

2 Comments

I thought of that before, but I thought something wouldn't work with it. Thanks :)
hm... but why? i thought that storing date in special datetime field will solve all the problems. with ID - how can you select all for e.g. 'yesterdays' posts?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.