Chapter 3. Dates and Times


Displaying and manipulating dates and times seems simple at first but gets more difficult depending on how diverse your users are. Do your users span more than one time zone? Probably so, unless you are building an intranet or a site with a very specific geographical audience. Is your audience frightened away by timestamps that look like “2015-07-20 14:56:34 EDT” or do they need to be calmed with familiar representations like “Saturday July 20, 2015 (2:56 P.M.)”? Calculating the number of hours between today at 10 A.M. and today at 7 P.M. is pretty easy. How about between today at 3 A.M. and noon on the first day of next month? Finding the difference between dates is discussed in Recipes and .

These calculations and manipulations are made even more hectic by daylight saving (or summer) time (DST). Because of DST, there are times that don’t exist (in most of the United States, 2 A.M. to 3 A.M. on a day in the spring) and times that exist twice (in most of the United States, 1 A.M. to 2 A.M. on a day in the fall). Some of your users may live in places that observe DST, some may not. Calculating Time with Time Zones and Daylight Saving Time provides ways to work with time zones and DST.

Programmatic time handling is made much easier by two conventions. First, treat time internally as Coordinated Universal Time (abbreviated UTC and also known as GMT, Greenwich Mean Time), the patriarch of the time-zone family with no DST or summer time observance. ...

Get PHP Cookbook, 3rd Edition now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.