In this article, we will see how to convert date from one format to another format.

For example : d-m-yyyy to m-d-yyyy

By using the date() function we can convert the date from one format to another format.

The date() function takes two arguments:

  1. Format of the ouput date.
  2. Unix timestamp representing the input date.

The following example shows how to convert date from dd-mm-yyyy to the format yyyy-mm-dd.

$inputDate = "31-12-2021";
$format = "d-m-Y";
$timestamp = strtotime($inputDate);
$outputDate = date("Y-m-d", $timestamp);

Here is the line by line explanation of how the above code works.

  • The first line assigns the date in the format dd-mm-yyyy to the variable $inputDate.
  • The second line assigns the input date’s format to the variable $format.
  • The third line converts the input date to a Unix timestamp using the strtotime() function.
  • The fourth line converts the timestamp to the desired output format of yyyy-mm-dd using the date() function.

Please be noted that in the format string passed to date() function, Y represent year, m represents month, and d represents the day of the month.

Categorized in:

Tagged in: