Code Snippet

Home » Code Snippets » PHP » Change Date from dd/mm/yyyy to yyyy-dd-mm

Change Date from dd/mm/yyyy to yyyy-dd-mm

Conversion

$date_array = explode("/",$date); // split the array
$var_day = $date_array[0]; //day seqment
$var_month = $date_array[1]; //month segment
$var_year = $date_array[2]; //year segment
$new_date_format = "$var_year-$var_day-$var_month"; // join them together

Possibly a more MySQL friendly format in some circumstances.

Change period-separated to slash-separated or vice versa (and reverse order)

Convert date from YYYY/MM/DD to DD.MM.YYYY (and from DD.MM.YYYY to YYYY/MM/DD)

/**
 * @param string $date (d.m.y, y-m-d, y/m/d)
 * @return string|bol
 */

function convertDate($date) {
       // EN-Date to GE-Date
       if (strstr($date, "-") || strstr($date, "/"))   {
               $date = preg_split("/[\/]|[-]+/", $date);
               $date = $date[2].".".$date[1].".".$date[0];
               return $date;
       }
       // GE-Date to EN-Date
       else if (strstr($date, ".")) {
               $date = preg_split("[.]", $date);
               $date = $date[2]."-".$date[1]."-".$date[0];
               return $date;
       }
       return false;
}

Subscribe to The Thread

  1. kukat

    date(‘Y-m-d’, strtotime(’23/10/2009′));

  2. Fabricio Anzorena

    implode(‘-’, array_reverse(explode(‘/’,$date)));

    Won’t have the 1970 limit problem of the timestamp.

  3. Emma Davis

    Your last line of code in preparing the date for databse is incorrect as it puts the day before the month:

    $new_date_format = “$var_year-$var_day-$var_month”;

    Should be:

    $new_date_format = “$var_year-$var_month-$var_day”;

  4. Prashant Palikhe

    Fabricio’s answer is much more elegant and works just fine:)

  5. nile

    kukat’s is the best though.

Speak, my friend

At this moment, you have an awesome opportunity* to be the person your mother always wanted you to be: kind, helpful, and smart. Do that, and we'll give you a big ol' gold star for the day (literally).

Posting tips:
  • You can use basic HTML
  • When posting code, please turn all
    < characters into &lt;
  • If the code is multi-line, use
    <pre><code></code></pre>
Thank you,
~ The Management ~