martincarlin87
martincarlin87

Reputation: 11042

PHP Date Bug When Using Code with Translated Dates

Yet another PHP date question for everyone - I have the current code for an English version of my site which works perfectly:

$article = &$articles[$i];

if($currentdate != date("F Y", strtotime($article->getDate()))) {   
    $currentdate = date("F Y", strtotime($article->getDate()));                 
    $current_content1 .= "<div class='press-articles-heading'>" . $currentdate . "    </div>";
}   

Basically what this does is pulls records from a db and compares the date so that the month header is only displayed once, e.g. July 2012 and then all the records for the month, and then June 2012 etc.

If I use the same code on a non-English version of a site I get a bug:

$article = &$articles[$i];

if($currentdate != date("F Y", strtotime($article->getDate()))) {   
    $currentdate = strftime("%B %Y", strtotime($article->getDate()));                 
    $current_content1 .= "<div class='press-articles-heading'>" . $currentdate . "</div>";
}   

What happens here is I get the month header for every db record despite them being the same.

Can't see where the bug is, has anyone any ideas?

Any help is much appreciated.

Update

I did try a few things before posting the question but thought best to leave it out in order to keep the question simple.

I did try the following:

$article = &$articles[$i];

if($currentdate != date("F Y", strtotime($article->getDate()))) {   
    $translated_date = strftime("%B %Y", strtotime($article->getDate()));                 
    $current_content1 .= "<div class='press-articles-heading'>" . $translated_date . "</div>";
}

But that didn't solve it

Upvotes: 1

Views: 86

Answers (2)

Grampa
Grampa

Reputation: 1643

Try this:

$article = &$articles[$i];

$timeString = strtotime($article->getDate());
$numericDate = strftime('%m %Y', $timeString);

if($currentDate != $numericDate) {
    $currentDate = $numericDate;
    $translatedDate = strftime('%B %Y', $timeString);                 
    $current_content1 .= "<div class='press-articles-heading'>" . $translatedDate . "</div>";
}

This will make the comparisons based on the numeric value of the month and year, but it will display the localized text value. I used extra variables to cache some date parsing results.

Upvotes: 1

deceze
deceze

Reputation: 522081

You're comparing the value of date('F Y') to the value of strftime('%B %Y'). Those probably won't match.

Upvotes: 0

Related Questions