PHP’s DateTime built-in class vs. Zend_Date
If you ever wanted a reason not to use PHP’s built-in DateTime class or to lie awake wondering about your code that uses it, here’s a good one. I’ve not looked into why this happens but 31st October minus one month gives 1st October. It should give 30th September. Zend_Date works in this respect:
Here’s a session showing this in action:
bob@desktop:~$ php -a
Interactive shell
php > $m = new DateTime();
php > echo $m->format( 'r' );
Mon, 31 Oct 2011 09:39:12 +1300
php > echo $m->modify('-1 month')->format( 'r' );
Sat, 01 Oct 2011 09:39:12 +1300
*cries*
bob@desktop:~$ php -a
Interactive shell
php > $m = new Zend_Date();
php > echo $m;
Oct 31, 2011 9:47:50 AM
php > echo $m->sub( 1, Zend_Date::MONTH );
Sep 30, 2011 9:48:25 AM
*correct*
5 Comments
Other Links to this Post
RSS feed for comments on this post. TrackBack URI
By
Gareth Redman, October 31, 2011 @ 4:35 pm
Calendar arithmetic is weird. None of JavaScript, .NET, or Python seem to support arithmetic with months at all.
Haskell gives you both `addGregorianMonthsClip` and `addGregorianMonthsRollOver`. The roll-over version matches the built-in PHP result, and the clip version matches Zend. Good times.
By
GuruBob, November 3, 2011 @ 7:48 am
Cheers G … thanks for the clarification.
In the end I was just far more explicit with my code. I just needed to know what the previous month was so I took the current month, found the first day of it and then subtracted a month from that date.
You can do it manually but it’s messy having to check < 1 and make it 12.
By
Brett Taylor, November 5, 2011 @ 11:01 am
Technically that’s correct, if you count the 31st October as 1st November.
1st November – 1 month = 1st October.
By
Brett Taylor, November 5, 2011 @ 11:02 am
Probably a bug in the whole ’30 days has September’ function
By
Pogo Cheats, January 18, 2012 @ 5:07 pm
I like your blog theme. style? Is it free to download? Regards