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

Visual Presentation:

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

Sample Solution:

PHP Code:

<?php
$odate = "2012-09-12"; // Assign a date string "2012-09-12" to the variable $odate
$newDate = date("d-m-Y", strtotime($odate)); // Convert the date string $odate to a new date format "d-m-Y" using strtotime() and store it in $newDate
echo $newDate."\n"; // Output the new date stored in $newDate followed by a newline character ("\n")
?>

Output:

12-09-2012

Explanation:

In the exercise above,

  • $odate = "2012-09-12";: This line assigns the date string "2012-09-12" to the variable '$odate'. This string represents September 12, 2012.
  • $newDate = date("d-m-Y", strtotime($odate));: This line converts the date string $odate to a new date format "d-m-Y" using the "strtotime()" function. The "strtotime()" function parses the date string and returns a Unix timestamp representing the same date and time. The "date()" function formats this timestamp into the specified format "d-m-Y" and stores the result in the variable "$newDate".
  • echo $newDate."\n";: This line outputs the new date stored in '$newDate', followed by a newline character "\n".

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 convert scientific notation to an int and a float.
Next: Write a PHP script to get the information regarding memory usage in KB or MB etc.

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-math-exercise-5.php