Dates and Times in PHP
We are all connected – through our relationships, through location, and by time. We share one clock with the same 24 hours. We just start our days at different points on that clock. Those points are represented by time zones.
We all think about time differences on a regular basis. Developers have the responsibility working with dates and times in code. In PHP, that’s usually means a combination of the date(), time(), strtotime(), and localtime() functions. However, there’s a better way — PHP’s Date/Time classes. You’ll learn how to work with them, to make your experience of handling dates and times easier. The DateTime class was introduced in PHP 5.2.0, so it’s save to use – even if you’re stuck on a stone age install of WordPress.
DateTime
// The current time in the current timezone $now = new DateTime(); $alsoNow = new DateTime('now');
The DateTime constructor can take at most 2 parameters, both of which are optional. The first parameter — a date/time string — represents a point in time. The 2nd parameter — the timezone — is optional. In the above example, those 2 values represent the current date and time. You’ll notice that neither of the instances in the above example use the 2nd parameter. When the 2nd parameter is not passed in, the systems default timezone is used, which is determined by the value specified in the php.ini file.
There are more moments you can use than now
. There are a wide variety of formats, in fact. Here are a few examples representing the same date.
// 'mm/dd' American date format $oct20 = new DateTime('10/20'); // mm/dd/yy American date format with year $oct20 = new DateTime('10/20/2017'); // yyyy-mm-dd ISO date format $oct20 = new DateTime('2017-10-20'); // Month first $oct20 = new DateTime('oct 20'); // Day first $oct20 = new DateTime('20 oct');
There might be a time when the format you want to use, cant be figured out by the constructor. If that happens you can use the createFromFormat() method. It lets you describe the format your preferred date style to create a DateTime object.
$customDate = '2017.oct.03 13:08:23'; $dateFormat = 'Y.M.d H:i:s'; $myDate = DateTime::createFromFormat($dateFormat, $customDate, );
Using the Time Zone
One mistake commonly made by developers is trying to calculate the current time based on their offset from UTC. While it seems to work, this kind of code will cause you problems. It doesn’t handle daylight savings time. Also, not all offsets from UTC are whole number of hours from UTC.
// Bad Practice - DON'T DO THIS $secondsInAnHour = 3600; $seattle = 8; // hours from UTC $seattleTime = time() - ($seattle * $secondsInAnHour); echo date('c', $seattleTime);
Instead, it’s better to use the DateTime classes in PHP. Using them will greatly simplify your experience, while increasing your effectiveness.
Here’s how you can convert the time from one timezone to another timezone.
$nowSeattle = $nowUniversalTime->setTimezone(new DateTimeZone('US/Pacific')); echo $nowSeattle->format(DATE_ISO8601) . PHP_EOL;
I’d recommend creating an object for each timezone you want to use. It’ll make it easier to reuse, and make your code more readable. For example.
$tzUTC = new DateTimeZone('UTC'); $tzPacific = new DateTimeZone('America/Los_Angeles'); $tzEastern = new DateTimeZone('America/New_York');
Look as the list of supported timezones, to find one for your area. FYI, the ‘America’ category is used for cities in North America and South America.
DateInterval
A date interval is the duration between two DateTime objects. You can determine a date interval by providing 2 DateTimes objects. However, you can use a DateTime and a DateInterval to determine a new DateTime.
Lets start by using two DateTime objects. Here’s how to calculate the number of days until Christmas.
$christmas = new DateTime('dec 25', new DateTimeZone('US/Pacific')); $untilChristmas = $nowSeattle->diff($christmas); echo "Only {$untilChristmas->days} days until Christmas" . PHP_EOL;
If you wanted to use a date interval to calculate a new date, here’s how to do it.
$now = new DateTime('now', new DateTimeZone('America/Los_Angeles')); $sevenDays = new DateInterval('P7D'); // a Period of 7 days $aWeekFromToday = $now->add($sevenDays); echo $aWeekFromToday->format(DATE_ISO8601) . PHP_EOL;
Conclusion
So that’s an overview of how to use major Date/Time classes in PHP. You learned a couple of ways to create a DateTime object, as well as how to use time zone objects. As always, there’s more to learn, but this will simplify things as get you started.