This tutorial uses PHP strtotime() and date() functions to convert date time format. For example you have stored a date YYYY-MM-DD format in a variable and need to change this to MM-DD-YYYY format.
We can achive this by converting date first to seconds using strtotime() function. After that reconstruct date to any format using date() function. Below is few examples of conversion:
1. Change YYYY-MM-DD => MM-DD-YYYY
Here we have date yyyy-mm-dd (“2019-01-15”) format and converting it to mm-dd-yyyy (“01-15-2019”) format.
1 2 3 4 | $origDate = "2019-01-15"; $newDate = date("m-d-Y", strtotime($origDate)); echo $newDate; |
Output:
01-15-2019
2. Change YYYY-MM-DD => DD-MM-YYYY
Here we have date yyyy-mm-dd (“2019-01-15”) format and converting it to dd-mm-yyyy (“15-01-2019”) format.
1 2 3 4 | $origDate = "2019-01-15"; $newDate = date("d-m-Y", strtotime($origDate)); echo $newDate; |
Output:
15-01-2019
3. Change DD/MM/YYYY => YYYY-MM-DD
If you have slashes in date format like “15/01/2019” and need to convert / with hyphens (-). The following example will help you to convert DD/MM/YYYY (“15/01/2019”) to YYYY-MM-DD (2019-01-15).
1 2 3 4 5 | $origDate = "15/01/2019"; $date = str_replace('/', '-', $origDate ); $newDate = date("Y-m-d", strtotime($date)); echo $newDate; |
Output:
2019-01-15
10 Comments
Thanxx
Hello Paul, this is a great tutorial but I have question regarding my current problem in MySQL and PHP in finding the difference between 2 dates(variables: start date and end date). MySQL date format is YYYY-mm-dd while in bootstrap is mm/dd/YYYY. I want to calculate the difference between two dates from MySQL and display the output from PHP. I hope you could help me on this Paul ?
what do i do if i want to convert any format into a specified format
whether it is in string format i.e february or feb
whether it is 2 or 02
whether it is short form of year i.e 1973 or 73
or format listed in
https://docs.oracle.com/cd/E41183_01/DR/Date_Format_Types.html
Great article however what do you do if the original date is in the format of a posted string ie let’s say “15/01/2019” .
$origDate = $_POST[‘Date1’];
$date = str_replace(‘/’, ‘-‘, $origDate );
$newDate = date(“Y-m-d”, strtotime($date));
echo $newDate;
Good article this post helped me, thanks very good.
good but i want to convert
29-Apr-2019 to Apr 29, 2019
how to do that?
date(“d F, Y”, strtotime($date));?>
Excellent!!! I have found that I looked for. But, how can I do the name of months in other language?
I like this website very much, Its a real nice situation to
read and receive info.
Thank you …