Backend Development 4 min read

Using PHP date() Function to Format Dates and Times

This article explains PHP's versatile date() function, detailing its syntax, required format parameter, optional timestamp argument, and demonstrates numerous usage examples—including retrieving current date, time, individual components, and formatting specific timestamps—highlighting its importance for backend web development.

php中文网 Courses
php中文网 Courses
php中文网 Courses
Using PHP date() Function to Format Dates and Times

PHP is a widely used server‑side language that provides powerful date and time handling. The date() function returns the current date and time or a specified timestamp.

The syntax is date(format, timestamp) , where format is required and timestamp is optional; if omitted, the current time is used.

Common format strings include:

Y-m-d H:i:s – full date and time

Y-m-d – date only

H:i:s – time only

Y – year

m – month

d – day

l – weekday name

Example code demonstrating these usages:

<?php
// 1. Return current date and time
echo date("Y-m-d H:i:s"); // e.g., 2022-10-31 19:30:15
echo "<br>";

// 2. Return current date
echo date("Y-m-d"); // e.g., 2022-10-31
echo "<br>";

// 3. Return current time
echo date("H:i:s"); // e.g., 19:30:15
echo "<br>";

// 4. Return year
echo date("Y"); // e.g., 2022
echo "<br>";

// 5. Return month
echo date("m"); // e.g., 10
echo "<br>";

// 6. Return day
echo date("d"); // e.g., 31
echo "<br>";

// 7. Return weekday name
echo date("l"); // e.g., Monday
echo "<br>";

// 8. Use a timestamp to get a specific date and time
$timestamp = mktime(10, 30, 0, 12, 25, 2022);
echo date("Y-m-d H:i:s", $timestamp); // e.g., 2022-12-25 10:30:00
echo "<br>";

// 9. Convert a time string to a timestamp and format it
$time_str = "2022-12-25 10:30:00";
$timestamp = strtotime($time_str);
echo date("Y-m-d H:i:s", $timestamp); // e.g., 2022-12-25 10:30:00
echo "<br>";
?>

The date() function returns a string, so it can be directly output with echo . By choosing appropriate format strings, developers can obtain any required date or time information, making the function a flexible and essential tool in PHP web development.

backendPHPDateTimedate formattingdate functionphp tutorial
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.