Date with PHP

One of the site I am working on needs to hide a promotion ads after 12:00 midnight local time at the end of October. At first, it looks straight forward as comparing the current date to Nov 1 and hide the ads. This can be easily done as below on the php page concerned:

< ?php if (strtotime(date("Y-m-d")) < strtotime("2010-11-01")) { ?>
Ads to hide after midnight Oct 31st goes here...
< ?php } ?>

Well, it was fine if the server is located here in HK, but it’s not. Noticed this when I was checking the code and tested it for today’s date. It turns out that the server is in a time zone in GMT -4 hours and HK is in GMT +8 hours. This means a difference of 12 hours.

Option 1, hard code the difference in the date being compared. This is the easiest and fastest. but not elegant and might be cause error for other coders maintaining the code later…might not be really a big deal…it’s only 12 hours difference. After noon it will work…It’s ok right? well maybe not…people will not be happy with that! 🙂

Option 2, capture the server’s offset from GMT and and adjust for HK offset of 8 hours and add to the date being compared. This is more complicated.

As it turns out, my solution is even much simplier, I end up using ISO 8601 date format which was added in PHP 5 and represented the date as 2010-11-01T00:00:00+08:00 with the +08:00 the GMT offset of Hong Kong. Here’s the code:

< ?php if (strtotime("now")) < strtotime("2010-11-01T00:00:00+08:00")) { ?>
Ads to hide after midnight Oct 31st goes here...
< ?php } ?>

This entry was posted in Web Development. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *