In PHP, as with most programming language, you'll need to run through logical things like this in your head all the time. The steps to solving this issue would normally follow a three step process:
- Knowing what you want. This is the step that you basically have laid out for us. You want to have a relative date system. A timestamp will be converted either into the number of hours since a post was submitted or the number of days since it was submitted.
- Thinking about the logic. This is normally the most crucial step. Once you know what you want, it can be sometimes hard to pin exactly what you're trying to execute within the actual code. Sometimes, utilizing pseudo-code will help you with this step.
- Programming it. This is where your logic shows itself in the editor. Occasionally, you may need to readjust things, but if you've thought everything through, this step doesn't need to be that hard.
Since you've already thought through the first step, the next is to think about how the logic may come to life through real life code. Setting up a psuedo-code example, I'd do something like the following.
if timeElapsed < 24 hours
print hoursElapsed
else
print daysElapsed
Note that we didn't quite set up the ternary operator, but we have the bare minimum and can easily convert the above to PHP and fit into the code environment that you've already set up. Thinking through this, we have some variables that we'd need to define, but we can do that in the PHP:
$elapsedTime = time() - $news_item_timestamp; //difference in time from post to now
$relativeDate = ($elapsedTime < 86400) ? round($elapsedTime/3600) . " minutes ago" : round($elapsedTime / 86400) . " days ago";
// 86400 seconds = 60 seconds * 60 minutes * 24 hours = 1 day
// 3600 seconds = 60 seconds * 60 minutes = 1 hour