Chapter 6. Dates and Times

Manipulating dates and times is one of the most complicated tasks you can do in any language, let alone in PHP. This is simply because time is relative—now will differ from one user to the next and potentially trigger different behavior in your application.

Object Orientation

PHP developers will work primarily with DateTime objects in code. These objects work by wrapping a particular instance in time and provide a wide variety of functionality. You can take the differences between two DateTime objects, convert between arbitrary time zones, or add/subtract windows of time from an otherwise static object.

Additionally, PHP supports a DateTimeImmutable object which is functionally identical to DateTime but cannot be modified directly. Most methods on a DateTime object will both return the same object and mutate its internal state. The same methods on DateTimeImmutable leave the internal state in place but return new instances representing the result of the change.

Note

Both date/time classes extend an abstract DateTimeInterface base class, making the two classes nearly interchangeable within PHP’s date and time functionality. Everywhere you see DateTime in this chapter you could use a DateTimeImmutable instance instead and achieve similar if not identical functionality.

Time Zones

One of the most challenging problems any developer will face is working with time zones, particularly when daylight saving time is involved. On the one hand, it’s easy to ...

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.