How to convert a date format in PHP
Today, we’ll discuss how to convert a date format in PHP. For example if we have date in YYYY-MM-DD format and need to convert it to DD-MM-YYYY format.
Using built-in PHP functions strtotime() and date(), we can easily convert date format.
- strtotime() function – To convert any textual datetime to a Unix timestamp.
- date() function – To convert timestamp into desired date format.
You can also check Add or Subtract days, month and year to a date using PHP.
Let’s start with an example.
Convert a date format
1. Convert YYYY-MM-DD to DD-MM-YYYY
In the following example, we will change the date from yyyy-mm-dd format to dd-mm-yyyy.
1 2 3 4 5 6 7 | <?php $originalDate = "2021-01-07"; $newDate = date("d-m-Y", strtotime($originalDate)); print_r($newDate); ?> // Output: 07-01-2021 |
2. Convert YYYY-MM-DD to MM-DD-YYYY
In this second example, we will change the date from yyyy-mm-dd format to mm-dd-yyyy.
1 2 3 4 5 6 7 | <?php $originalDate = "2021-01-07"; $newDate = date("m-d-Y", strtotime($originalDate)); print_r($newDate); ?> // Output: 01-07-2021 |
3. Convert DD/MM/YYYY to YYYY-MM-DD
In the last example, we will change the date from dd/mm/yyyy format to yyyy-mm-dd.
1 2 3 4 5 6 7 8 | <?php $originalDate = "07/01/2021"; $originalDate = str_replace('/', '-', $originalDate ); $newDate = date("Y-m-d", strtotime($originalDate)); print_r($newDate); ?> // Output: 2021-01-07 |
That’s it for today.
Thank you for reading. Happy Coding..!! 🙂