Zend_Date Problems with MySQL

Have you ever seen this problem?

I had a MySQL Date in my DB (2012-08-31). This is the 31st of August.

$expirydate = new Zend_Date($mysql_date);
 echo $expirydate;

Returned 31st August as expected.

But if the date is the 4th August (2012-08-04), the same code as above will echo out the 8th April!
Zend_Date automatically tries to guess the format, and mistakenly guessed Y/d/m !
I came across this problem when I tried to compare dates:

 $expirydate = new Zend_Date($mysql_date);
 $today = new Zend_Date();
     //today is beyond expiry date

The Zend Docs weren’t very clear, and i thought maybe it should have been the other way around, $expirydate->isLater($today)
But it’s not.

All that is required is to set the format in the constructor. For MySQL Dates, the format is ISO_8601:

$expirydate = new Zend_Date($mysql_date,Zend_Date::ISO_8601);

Problem solved. The moral of the story? Make sure you declare the format of the dates!!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s