O'Reilly logo

Learning PHP 5 by David Sklar

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 9. 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 a user logged in so that you can tell them things such as "fifteen new messages were posted since you last logged in."

Handling dates and times properly in your programs is more complicated than handing 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.

A programming convention that simplifies date and time calculation is to treat a particular time and date as a single value: the number of seconds that have elapsed since midnight on January 1, 1970. This value is called an epoch timestamp. The choice of January 1, 1970 is mostly arbitrary. But, as is the way with conventions, since lots of other people are doing it, you've got to do it, too. Fortunately, PHP provides plenty of functions for you to deal with epoch timestamps.

In this book, the phrase time parts (or date parts or ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required