Karem
Karem

Reputation: 18103

PHP: write out year if it's not from the current year, timestamp

I wish to only write out(Y) the year, if only its not from the current year we're on.

function get_day_name($timestamp) {
    $date = date('j-m-Y', $timestamp);
    if($date == date('j-m-Y')) {
      $day_name = 'Today';
      echo 'idag ';
    } else if($date == date('j-m-Y',time() - (24 * 60 * 60))) {
      $day_name = 'Yesterday';
      echo 'igår ';
    }else{
    # How can i check here whether the $timestamp is from this year or last year?
    # If it is from this year then it shouldnt write out the "Y" in $date
    echo $date;
    }
}

Upvotes: 1

Views: 2469

Answers (2)

sberry
sberry

Reputation: 132078

Based on the comment in your original post

# How can i check here whether the $timestamp is from this year or last year?

I thought you were asking how you could check to see if the timestamp year was from this year or last year. So, I thought you meant you wanted to know, for example, if the year was 2011 or 2010. What you really want to know is whether the timestamp year is from this year, or any other year, be it 2010, 2009, etc.

This was my first answer, based on my misunderstanding...

$current_year = date('Y');
$timestamp_year = date('Y', $timestamp);
if ($timestamp_year == $current_year || $timestamp_year == $current_year - 1)

This is how you would want to do it:

if (date('Y') == date('Y', $timestamp)) 

Upvotes: 2

GZipp
GZipp

Reputation: 5416

You could subtract the $timestamp year from the current year (or vice versa). If they're different, the result will be non-zero, resolving to true; if they're the same, the result will be zero, resolving to false.

if (date('Y') - date('Y', $timestamp)) {
    echo date('j F Y', $timestamp);
} else {
    echo date('j F', $timestamp);
}

Upvotes: 0

Related Questions