-2

I just got this figured out:

$dates = date(" d-m-y",$forum_tid);
if ($dates == date(' d-m-y')) {
    $day_name = 'This day';
} else if($dates === date(" d-m-y", strtotime("-1 day"))) {
   $day_name = 'Yesterday';
} else {
    $day_name = 'Another day';
}
echo "$day_name";

Now this runs by 24 hours clock-system. Now I want it to work by dates. (If the time is the same day, it says "This day", if it was the date before f.ex 23-08-13, then it shows "Yesterday")

How exactly do I do this? Hope this is a question more people is wondering about!

Marius
  • 27
  • 1
  • 4
  • 2
    You should really be using [DateTime](http://www.php.net/manual/en/class.datetime.php) for this. – Mike Aug 23 '13 at 22:04
  • Yes, but how exactly do I do that in this purpose? – Marius Aug 23 '13 at 22:07
  • I have been told that you can [learn quite a bit from reading about it](http://php.net/DateTime). It is a little old-fashioned, but it works for some people. – Sverri M. Olsen Aug 23 '13 at 22:15

2 Answers2

1

With the DateTime class:

$date = new DateTime();
$date->setTimestamp($forum_tid);

$today = new DateTime();
$yesterday = new DateTime('-1day');

switch(TRUE) {

    case $today->format('m-d') === $date->format('m-d'):
        $day_name = 'This day';
    break:

    case $yesterday->format('m-d') === $date->format('m-d'):
        $day_name = 'Yesterday';
    break;

    default:
        $day_name = 'Another day';

}

echo "$day_name";
hek2mgl
  • 152,036
  • 28
  • 249
  • 266
  • I've never seen a switch like that. To me using `if/else` would be a bit more readable. But... to each his own. – Mike Aug 23 '13 at 22:18
  • @Mike Using `switch(TRUE)` enables you to have strict comparisons in switch statements.. Otherwise switch treats the case statements like `==` instead of `===`. I really often use it because of this and because I think this is more readable. But however in this case a if/else would work as well. Check my answer here for more information: http://stackoverflow.com/a/18346764/171318 – hek2mgl Aug 23 '13 at 22:22
-1

Do not use === for string comparisons.

You can get 12 o'clock with

strtotime(date("Y-m-d"));

So you could do:

if(strtotime($mydate) > strtotime(date("Y-m-d"))) {
    echo "Today";
} elseif(strtotime($mydate) > strtotime(date("Y-m-d", strtotime("-1 day")))) {
    echo "Yesterday";
} elseif(strtotime($mydate) > strtotime(date("Y-m-d", strtotime("-1 week")))) {
    echo "In the last week";
} else {
    echo "Older";
}
Dave
  • 386
  • 2
  • 8