How to Use the PHP date_format() Function

09/09/2021

Contents

In this article, you will learn how to use the PHP date_format() function.

PHP date_format() Function

The date_format() function in PHP is used to format a date string into a specified format. By specifying a format string, you can control exactly how the date string is displayed. It takes two arguments: the date string and the format string.

Here’s an example of how to use the date_format() function:

<?php
  $date = date_create("2022-12-29");

  // display the date in the format "Y/m/d"
  echo date_format($date, "Y/m/d");

  // display the date in the format "Y-m-d"
  echo date_format($date, "Y-m-d");

 // display the date in the format "d-m-Y"
 echo date_format($date, "d-m-Y");

 // display the date as "29th December 2022"
 echo date_format($date, "jS F Y");
?>

In the examples above, you can see how the format string is used to control the way the date string is displayed. The format codes used in the format string are similar to the codes used in the date() function, but with some additional codes available. You can find a full list of format codes in the PHP manual:
https://www.php.net/manual/en/function.date.php

It’s also possible to use the date_format() function with custom date strings. For example:

<?php
  $date = date_create("2022-12-29 12:00:00");
  echo date_format($date, "Y-m-d H:i:s");
?>

In this example, a custom date string “2022-12-29 12:00:00” is created and then formatted using the date_format() function.