Chapter 3. Dates and Times

Introduction

Displaying and manipulating dates and times seems simple at first but gets more difficult depending on how diverse and complicated 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 “2002-07-20 14:56:34 EDT” or do they need to be calmed with familiar representations like “Saturday July 20, 2000 (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 Recipe 3.6 and Recipe 3.7.

These calculations and manipulations are made even more hectic by daylight saving (or summer) time (DST). Thanks to DST, there are times that don’t exist (in most of the United States, 2 A.M. to 3 A.M. on the first Sunday in April) and times that exist twice (in most of the United States, 1 A.M. to 2 A.M. on the last Sunday in October). Some of your users may live in places that observe DST, some may not. Recipe 3.12 and Recipe 3.13 provide 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 ...

Get PHP Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.