Chapter 15. Handling Dates and Times

Dates and times are all over the place in a web application. In a shopping cart, you need to handle shipping dates of products. In a forum, you need to keep track of when messages are posted. In all sorts of applications, you need to keep track of the last time each user logged in so that you can tell them things like “15 new messages were posted since you last logged in.”

Handling dates and times properly in your programs is more complicated than handling strings or numbers. A date or a time is not a single value but a collection of values—month, day, and year, for example, or hour, minute, and second. Because of this, doing math with them can be tricky. Instead of just adding or subtracting entire dates and times, you have to consider their component parts and what the allowable values for each part are. Hours go up to 12 (or 24), minutes and seconds go up to 59, and not all months have the same number of days.

To ease this burden, PHP provides you with a class, DateTime, that encapsulates all the information about a specific point in time. With the methods of this class, you can print out a date or time in the format of your choice, add or subtract two dates, and work with time intervals.

In this book, the phrase time parts (or date parts or time-and-date parts) means an array or group of time-and-date components such as day, month, year, hour, minute, and second. Formatted time string (or formatted date string, etc.) means a string ...

Get Learning PHP 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.