w3resource

PHP Date Exercises : Convert a date from yyyy-mm-dd to dd-mm-yyyy

PHP date: Exercise-5 with Solution

Write a PHP script to convert a date from yyyy-mm-dd to dd-mm-yyyy.

Sample date : 2012-09-12

Sample Solution:

PHP Code:

<?php
// Original date in yyyy-mm-dd format
$odate = "2012-09-12";

// Converting the original date to a new format (dd-mm-yyyy)
$newDate = date("d-m-Y", strtotime($odate));

// Displaying the new formatted date
echo $newDate."\n";
?>

Output:

12-09-2012

Explanation:

The above PHP code takes a date string in the format "yyyy-mm-dd", converts it to the format "dd-mm-yyyy", and then prints the new formatted date. It achieves this by using the "strtotime()" function to parse the original date string and convert it into a Unix timestamp, and then the "date()" function to format the timestamp into the desired format. Finally, it prints the formatted date.

Flowchart :

Flowchart: Convert a date from yyyy-mm-dd to dd-mm-yyyy

PHP Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a PHP script to calculate the difference between two dates.
Next: Write a PHP script to convert the date to timestamp.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/php-exercises/php-date-exercise-5.php