php
  1. php-change-date-format

PHP Change Date Format

Syntax

date(string $format, int $timestamp = time()): string|false

Example

Suppose we have a date in Y-m-d format like 2022-12-31 and we want to change its format to d/m/Y.

$date = "2022-12-31";
$formatted_date = date("d/m/Y", strtotime($date));
echo $formatted_date;

Output

The output of the above code will be:

31/12/2022

Explanation

The date() function formats a local date and time into the specified string format. In the example, we use the strtotime() function which converts the date string to a Unix timestamp, and then pass the timestamp and the desired format string as arguments to the date() function.

Use

We can use the date() function to convert a date string from one format to another.

Important Points

  • date() function returns false on failure, so it's important to check for that.
  • The $timestamp parameter is optional and defaults to the current local time if not supplied.

Summary

In this tutorial, we learned how to change the date format of a string using PHP's date() function. We also learned how to convert a date string to a Unix timestamp using the strtotime() function.

Published on: