w3resource

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


5. Convert Date Format from yyyy-mm-dd to dd-mm-yyyy

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

For more Practice: Solve these Related Problems:

  • Write a PHP function to take a date in yyyy-mm-dd format, validate it, and output it in dd-mm-yyyy format using DateTime objects.
  • Write a PHP script to convert an array of dates from yyyy-mm-dd to dd-mm-yyyy format and then sort the resulting dates.
  • Write a PHP program to parse a date string, swap the day and year components, and output the result in a new format.
  • Write a PHP script to take user input for a date in ISO format and convert it to European format, handling invalid input gracefully.

Go to:


PREV : Convert Scientific Notation to Int and Float.
NEXT : Get Memory Usage Information.

PHP Code Editor:



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

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.