Skip to content

How do I Convert Date Format in PHP

Category
PHP
Versions & support
About PHP →
On this page

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.

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.

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).

Output:

2019-01-15

Rahul

Rahul Kumar is the founder and chief editor of TecAdmin.net. A Red Hat Certified Engineer (RHCE), he has worked in IT since 2009, with hands-on experience in Linux system administration, DevOps, web hosting, cloud platforms and automation. He started TecAdmin in 2013 to share practical, step-by-step guides, and leads its editorial work with one aim: making technical learning clear and useful for sysadmins, developers and beginners alike.

10 Comments

  1. 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 ?

  2. 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;

Leave a Reply

Your email address will not be published. Required fields are marked *


Back to top