PHP Convert Date Format From dd/mm/yyyy To yyyy-mm-dd
In this tutorial, I will show you how to convert PHP date format from dd/mm/yyyy to yyyy-mm-dd or PHP convert date format from dd-mm-yyyy to yyyy-mm-dd.
Suppose you are taking date input from user in human readable format and then you will need to add that date into your database table, but first you will need to convert date into correct date format which is acceptable by database table.
Steps to Convert PHP Date Format
Follow the below steps to convert PHP date format from dd/mm/yyyy to yyyy-mm-dd.
- Create a PHP convertDate() Function
- Pass the Date into convertDate() Function
1. Create a PHP convertDate() Function
First I will create a PHP convertDate() function to convert date in our desired format, copy paste the below in index.php
<?php
function convertDate($date) {
// EN-Date to GE-Date
if (strstr($date, "-") || strstr($date, "/")) {
$date = preg_split("/[\/]|[-]+/", $date);
$date = $date[2]."-".$date[1]."-".$date[0];
return $date;
}
return false;
}
?>
2. Pass the Date into convertDate() Function
Now, I will pass a sample date in this format (dd/mm/yyyy) to this function. Copy paste the below code in index.php
<p>
<strong>Input Date: </strong>
<?php
$input_date = "30/03/2023";
echo $input_date; ?>
</p>
<p>
<strong>Output Date: </strong>
<?php
$output_date = convertDate($input_date);
echo $output_date; ?>
</p>
The above code will generate the output like below:
Input Date: 30/03/2023
Output Date: 2023-03-30
Conclusion
I hope now you know how to convert PHP date format into your desired date format. It is a very easy way of PHP convert date format from dd/mm/yyyy to yyyy-mm-dd.
If you found this tutorial helpful, share it with your friends and developers group.
I spent several hours to create this tutorial, if you want to say thanks so like my page on Facebook, Twitter and share it.
Facebook Official Page: All PHP Tricks
Twitter Official Page: All PHP Tricks