Trusted answers to developer questions

What is the date() function in PHP?

Get the Learn to Code Starter Pack

Break into tech with the logic & computer science skills you’d learn in a bootcamp or university — at a fraction of the cost. Educative's hand-on curriculum is perfect for new learners hoping to launch a career.

The date() function in PHP is an inbuilt function that returns a formatted timestamp that can easily be understood.

This function is supported by PHP versions 4 and later.

Parameters

The date() method accepts two parameters:

  • format: This parameter indicates the format you want to display the date.

A list of acceptable formats can be found here.

  • timestamp: This argument is the Unix timestamp of reference. If no value is provided, the current local time will be used instead.

Return value

The date() function returns a formatted date string. If the value used for the timestamp parameter is not numeric, false is returned, and the E_WARNING error is raised.

Code

The code below shows how to use the date() function.

<?php
// setting the default timezone to use.
date_default_timezone_set('UTC');
//prints the current date and time
echo date('m-d-Y h:i:s:A')."\n";
// Prints something like: Wednesday
echo date("l") ."\n";
// Prints something like: Wednesday 10th of November 2021 03:12:46 AM
echo date('l jS \of F Y h:i:s A') ."\n";
// Prints: July 1, 2000 is on a Saturday
echo "July 1, 2000 is on a " . date("l", mktime(0, 0, 0, 7, 1, 2000))."\n";
?>

The date() function returns formatted date strings in the code above depending on the specified format.

The mktime() function used in line 1515 provides a pool of integers which the date() function can use to make a time string.

RELATED TAGS

php
web development
Did you find this helpful?