As part of an assignment in a Drupal course that I'm giving a UBC this fall, I asked the students to develop a small module that would create a block and output how many days there were until Christmas. This is a relatively simple task as it involves two Drupal hooks and a little bit of date manipulation.
As the students worked on the module it became clear to me that there were two ways in which to handle the date calculation part, that is it could be written in PHP version > 5.2 or in PHP version < 5.2.
DateTime class in PHP 5.2
PHP 5.2 introduced the DateTime class and with it an number of Date manipulation methods.
Some of these methods are only available in PHP >= 5.3. DateTime::diff being one of those.
Writing it for < PHP 5.2
As with all languages, there are a number of ways to approach such a task. I am not saying that my method is the only way to do it or even the most efficient way, it's just a quick example of one way to achieve the desired result. Below is an example of what could be in PHP < 5.2 to achieve the desired number of days:
- Create Christmas day as a timestamp
- Get the current date/time as a timestamp
- Get the difference between the two and divide by the number of seconds in a day
- Round that number down to the next lowest integer
Writing if for >= PHP 5.2
As a Drupal developer I've become more and more familiar with object orientated methods and so I was happy to see the Date class appear in PHP. Working it out using the Date methods feels somewhat cleaner and safer, given that there is an actual method called diff that does the calculation for you:
- Get Christmas as a DateTime object
- Get today as a DateTime object
- Get the difference between them
- Format it nicely
I like this as I don't have to round anything down and I don't have to divide by seconds in a day. I also have solid Date objects that I can manipulate and play around with.
Well how many days are there?
I guess I'll have to show that this actually works....
Days and counting :)
I think I'll be using the DateTime object a lot more in the future.