PHP Date & Time
In this page:
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
echo date('Y-m-d');
?>
Login to try C/C++/Java/PHP code in the editor
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
$timestamp = strtotime("+3 days");
echo date('Y-m-d', $timestamp);
?>
Login to try C/C++/Java/PHP code in the editor
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
$date = new DateTime('2024-02-29');
echo $date->format('Y-m-d');
?>
Login to try C/C++/Java/PHP code in the editor
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
$date = new DateTime('2024-01-01');
$date->modify('+1 month');
echo $date->format('Y-m-d');
?>
Login to try C/C++/Java/PHP code in the editor
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
date_default_timezone_set('America/New_York');
echo date('Y-m-d H:i:s');
?>
Login to try C/C++/Java/PHP code in the editor
Chapter Quiz — Complete all 24 topics to unlock
0/24 topics done
Complete these topics first:
- PHP Date & Time
- PHP Math Functions
- PHP JSON Handling
- PHP XML Handling
- PHP cURL Introduction
- PHP REST API Basics
- PHP Composer & Packages
- PHP Autoloading
- PHP Design Patterns
- PHP MVC Architecture
- PHP Security Best Practices
- PHP Performance Optimization
- PHP 8 New Features
- PHP Type Declarations
- PHP Match Expression Advanced
- PHP Fibers
- PHP Attributes
- PHP Magic Constants
- PHP Include & Require
- PHP Iterables
- PHP SimpleXML Parser
- PHP SimpleXML Get
- PHP XML Expat Parser
- PHP DOM Parser