Kathmandu,Nepal
Kathmandu,Nepal

Change date format in PHP

To convert the date-time format PHP provides strtotime() and date() function. We can change the date format from one format to another.

These are the built-in functions of PHP. The strtotime() first converts the date into the seconds, and then date() function is used to reconstruct the date in any format. Some examples are given below to convert the date format.

Change Date Format using the strtotime() funtion:

Example 1:
In this example, we use date 2021-08-15 in YYYY-MM-DD format, and we will convert this date to 15-08-2021

<?php
$orgDate = "2021-08-15";
$newDate = date("d-m-Y", strtotime($orgDate));
echo $newDate;
?>
Output:
15-08-2021

Example 2:
In this example, we use date 15-08-2021(DD-MM-YYY) format, and we will convert this date to 08-15-2021(MM/DD/YYYY) format.

<?php
$orgDate = "15-08-2021";
$newDate = date("m/d/Y", strtotime($orgDate));
echo $newDate;
?>
Output:
08/15/2021

Convert Date Format Using DateTime() function:

Example 1:
In this example, we use date 20-06-2021(DD-MM-YYYY) format, and we will convert this date to 2021-08-20(YYYY-MM-DD) format.

<?php
$orgDate = "20-06-2021";
$date = new DateTime($orgDate);
echo $date->format('Y-m-d');
?>

Output:
2021-06-20

Leave a Comment

Your email address will not be published. Required fields are marked *

×