Zend_Date not working it seems

609 Views Asked by At

I have been working with Zend_Date. Can anyone tell me if the behaviour below is normal? The returned months seem to be wrong. I have put the output in comments.

Thanks for any help!

$oDate = new Zend_Date();

$oDate->setMonth(1);
$oDate->setDay(15);
$oDate->setYear(2012);
echo $oDate->get(Zend_Date::DATETIME_FULL);//Sunday, January 15, 2012 8:24:59 PM Europe/Madrid

$oDate->setMonth(2);
echo $oDate->get(Zend_Date::DATETIME_FULL);//Thursday, March 15, 2012 8:25:20 PM Europe/Madrid

$oDate->setMonth(3);
echo $oDate->get(Zend_Date::DATETIME_FULL);//Thursday, March 15, 2012 8:25:40 PM Europe/Madrid

$oDate->setMonth(4);
echo $oDate->get(Zend_Date::DATETIME_FULL);//Tuesday, May 15, 2012 8:27:32 PM Europe/Madrid

$oDate->setMonth(5);
echo $oDate->get(Zend_Date::DATETIME_FULL);//Tuesday, May 15, 2012 8:28:05 PM Europe/Madrid
1

There are 1 best solutions below

0
On

The key is your original post date.

In months that have 31 days, if you are on the 31st day and setMonth() to a month with less days (i.e. Feb, Apr, June, Sep or Nov), it calculates the date as 31st of that Month which overflows to 1st of the next month.

The script above wasn't run as is, but was run:

  $oDate->setMonth();
  $oDate->setDay();
  $oDate->setYear();
  echo ...

for each month, hence the differing times.

The problem only manifests itself on 31st of a given month (hence why when the replies were posted, people could not replicate the problem), when setting to Apr, June, Sept or Nov; or 29th/30th/31st of a month when setting month to Feb.

You can fix this in the examples above by setting the day first, then the month (as the month will not then overflow).

You of course get the same problem in reverse, whereby you are in a month with < 31 days, and set days = 31, which overflows to 1st of the following month, meaning your date will then be on the 1st of the correct month!

Unfortunately, I am yet to find a simple fix for this (other than writing a new date class based on PHP's DateTime class).

Hope this helps!