w3resource

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


5. Date Format Conversion (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

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

For more Practice: Solve these Related Problems:

  • Write a PHP function to convert dates from yyyy-mm-dd format to dd/mm/yyyy format with customizable delimiters.
  • Write a PHP script that takes a date string in ISO format and outputs the same date in European format.
  • Write a PHP program to reformat an array of date strings from yyyy-mm-dd to dd-mm-yyyy.
  • Write a PHP script that reads a date from user input and converts it to dd-mm-yyyy format, handling input validation errors.

Go to:


PREV : Difference Between Two Dates.
NEXT : Convert Date to Timestamp.

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.