PHP Date Exercises: Convert a date 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:
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 :
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.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics