Categories
Programming

A comprehensive look at PHP5 DateTime

Don’t expect to find it here, but Laughine Meme posted the most comprehensive one I could find.  You would think that with the introduction in 5.2 of the DateTime and DateTimeZone objects, that date math would be a lot easier in PHP.  Unfortunately, the implementation isn’t as advanced as I’d expected, maybe a case of high expectations.  Dealing with dates,especially once timezones are involed can be very unintuitive, and this doesn’t seem to make it noticeably easier.

Beyond adding deltas (”+7 days”), the other common date math is comparing two datetimes, to find out which is more recent, and getting the difference between them. DateTime supports no methods for comparing two datetimes. The simplest solution for doing comparison is to compare epoch seconds.

Buried in the comments, is this most wise bit of advice:

For most everyday issues, use gmdate functions for storage and putenv(’TZ=wherever’) to make the local presentation correct and you’re done. Converting a stored gmdate (say MySQL date/time format) to localtime for a given date string is a matter of appending ‘+0000′ onto the SQL string, passing it through strtotime, and then use date() on the result. The +0000 forces strtotime into dealing with it as GMT instead of trying to act smart and adding your local offset. Should be easier, but that ain’t bad.