Convert date format yyyy-mm-dd => dd-mm-yyyy


I am trying to convert a date from yyyy-mm-dd to dd-mm-yyyy (but not in SQL); however I don't know how the date function requires a timestamp, and I can't get a timestamp from this string.

How is this possible?

2/2/2014 2:03:04 AM

Accepted Answer

Use strtotime() and date():

$originalDate = "2010-03-21";
$newDate = date("d-m-Y", strtotime($originalDate));

(See the strtotime and date documentation on the PHP site.)

Note that this was a quick solution to the original question. For more extensive conversions, you should really be using the DateTime class to parse and format :-)

3/1/2019 3:23:10 PM

If you'd like to avoid the strtotime conversion (for example, strtotime is not being able to parse your input) you can use,

$myDateTime = DateTime::createFromFormat('Y-m-d', $dateString);
$newDateString = $myDateTime->format('d-m-Y');

Or, equivalently:

$newDateString = date_format(date_create_from_format('Y-m-d', $dateString), 'd-m-Y');

You are first giving it the format $dateString is in. Then you are telling it the format you want $newDateString to be in.

Or if the source-format always is "Y-m-d" (yyyy-mm-dd), then just use DateTime:

    $source = '2012-07-31';
    $date = new DateTime($source);
    echo $date->format('d.m.Y'); // 31.07.2012
    echo $date->format('d-m-Y'); // 31-07-2012

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow