← Back to PHP Course | Chapter 14: Advanced PHP | Lesson 1 of 24

PHP Date & Time

Getting the Current Date and Time

The date() function formats the current time (or any Unix timestamp you pass it) according to a format string of letter codes, so date(Y-m-d) gives you a sortable ISO-style date instantly.

Example: Getting the Current Date and Time

php
<?php
echo date('Y-m-d');
?>

Creating Timestamps from Strings

strtotime() parses everyday English phrases like 'next Monday' or '+3 days' into a Unix timestamp, which is remarkably flexible for turning user-typed dates into something PHP can calculate with.

Example: Creating Timestamps from Strings

php
<?php
$timestamp = strtotime("+3 days");
echo date('Y-m-d', $timestamp);
?>

Working with the DateTime Class

The DateTime class wraps date handling in an object-oriented API that correctly accounts for tricky edge cases like leap years and daylight-saving shifts, which manual timestamp math tends to get wrong.

Example: Working with the DateTime Class

php
<?php
$date = new DateTime('2024-02-29');
echo $date->format('Y-m-d');
?>

Modifying Dates

DateTime's modify() method and the separate DateInterval class both let you shift a date forward or backward by a readable amount (like '+1 month'), which is far less error-prone than adding raw seconds.

Example: Modifying Dates

php
<?php
$date = new DateTime('2024-01-01');
$date->modify('+1 month');
echo $date->format('Y-m-d');
?>

Timezones in PHP

date_default_timezone_set() fixes the timezone your whole script assumes when it isn't told otherwise; without it, PHP falls back to a server default that may not match your users' expectations.

Example: Timezones in PHP

php
<?php
date_default_timezone_set('America/New_York');
echo date('Y-m-d H:i:s');
?>

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.