559

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?

AbraCadaver
  • 78,200
  • 7
  • 66
  • 87
matthy
  • 8,144
  • 10
  • 38
  • 47
  • Why would you want to do this? The former is the standard in most countries. http://www.qsl.net/g1smd/isoimp.htm – stesch Mar 21 '10 at 17:20
  • 24
    dd-mm-yyyy is the standard format in (most of) Europe at least when you need to present data to users. – Matteo Riva Mar 21 '10 at 17:23
  • 7
    dd-mm-yyyy in Australia and New Zealand too – Jonathan Day Dec 03 '11 at 12:45
  • 3
    mm-dd-yyyy in USA. @stesch: the former is standard in SQL. I'm not sure it's _standard_ in any country. :) – Herbert Dec 15 '11 at 06:38
  • 13
    Actually, the *standard* is yyyy-mm-dd as according to [ISO 8601](http://en.wikipedia.org/wiki/ISO_8601). – Jezen Thomas Mar 01 '13 at 07:43
  • 11
    The global "Standard" is yyyy-mm-dd, and should always be used by systems wherever possible. The order day, month, year is used by people in most of the world (except USA), but usually with slashes, not hyphens. To avoid confusion, I only separate YYYY-MM-DD with hyphens. Any other date format I will separate with slashes. This keeps things consistent. – rjmunro Mar 12 '13 at 11:49

18 Answers18

1188

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

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
richsage
  • 26,912
  • 8
  • 58
  • 65
  • 16
    What if I get this date 0000-00-00 from mySQL? it returns a wrong date like 31/12/1969 ... – Enrique Apr 29 '10 at 22:20
  • 4
    @Enrique: If you get 000-00-00 from MySQL, you should test against that FIRST before putting it through the conversion. Simples. – ShadowStorm Nov 04 '12 at 15:20
  • 2
    @SobinAugustine et al: strtotime() will convert the date string to a "Unix timestamp (the number of seconds since January 1 1970 00:00:00 UTC)", a format date() can understand and then convert from. So this will not work with a timestamp before 1970. – Samuel Lindblom Jan 30 '14 at 07:12
  • 1
    @SamuelLindblom no, its not like that, it will work before 1970. – Sobin Augustine Jan 30 '14 at 09:47
  • 1
    @SobinAugustine: You are right. It will however not work before 1901-12-14 so that still applies to why the dates listed above do not work. – Samuel Lindblom Jan 30 '14 at 13:02
  • @SamuelLindblom so again, thats my question,"what if the date is "1000-01-01" " there although i found out !! :) – Sobin Augustine Jan 30 '14 at 13:11
  • @SobinAugustine It also doesn't work for "Hello-How-Are-You".. smh – Dan Chase Nov 11 '18 at 18:05
  • 1
    What if original date is "2010-04-01" ? This could be both January 4th, or 1st April. – GeneCode Jan 15 '19 at 07:21
  • `$originalDate = "23/07/2020";$newDate = date("d-m-Y", strtotime($originalDate));` This is not working :( – TarangP Jul 23 '20 at 06:07
320

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:

<?php
    $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
?>
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
ceiroa
  • 5,833
  • 2
  • 21
  • 18
76

Use:

implode('-', array_reverse(explode('-', $date)));

Without the date conversion overhead, I am not sure it'll matter much.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Tim Lytle
  • 17,549
  • 10
  • 60
  • 91
  • Yeah, answered as you submitted yours I believe. Of course the error checking found in strtotime may be something useful. – Tim Lytle Mar 21 '10 at 18:44
  • 2
    Was useful for me in converting non-American date format... dd-mm-yyyy => yyyy-mm-dd See http://www.php.net/manual/en/datetime.formats.date.php – Chris Jacob Sep 01 '10 at 00:42
  • 2
    You can even call it again if you need to reverse the date format to its original form. Best answer indeed. :) – Pedro Araujo Jorge Mar 04 '14 at 15:17
  • @MatteoBononi'peorthyr' it doesn't solve all date-time issues. What if date format is `d-M-Y` and want to convert to `Y-m-d`. – krishna Jun 12 '15 at 06:51
  • Use explode `$date[0]."/".date('m', strtotime($date[1]))."/".$date[2]` is easier.. converter month to number, not work try strtotime is cause time zone. – KingRider Sep 02 '15 at 15:19
39
$newDate = preg_replace("/(\d+)\D+(\d+)\D+(\d+)/","$3-$2-$1",$originalDate);

This code works for every date format.

You can change the order of replacement variables such $3-$1-$2 due to your old date format.

Alper Sarı
  • 391
  • 3
  • 4
31
$timestamp = strtotime(your date variable); 
$new_date = date('d-m-Y', $timestamp);

For more, see the documentation for strtotime.

Or even shorter:

$new_date = date('d-m-Y', strtotime(your date variable));
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Kevin
  • 13,153
  • 11
  • 60
  • 87
30

Also another obscure possibility:

$oldDate = '2010-03-20'
$arr = explode('-', $oldDate);
$newDate = $arr[2].'-'.$arr[1].'-'.$arr[0];

I don't know if I would use it but still :)

Finduilas
  • 730
  • 1
  • 10
  • 28
Gabriel
  • 1,820
  • 2
  • 23
  • 31
  • 1
    I ended up using this because in our application, people would enter "99" if one of the fields (day, month, year) is unknown. Good approach if you have any "fake" dates in your data. – Voodoo Nov 20 '14 at 23:38
19

There are two ways to implement this:

1.

    $date = strtotime(date);
    $new_date = date('d-m-Y', $date);

2.

    $cls_date = new DateTime($date);
    echo $cls_date->format('d-m-Y');
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Raja Ram T
  • 854
  • 8
  • 8
16

Note: Because this post's answer sometimes gets upvoted, I came back here to kindly ask people not to upvote it anymore. My answer is ancient, not technically correct, and there are several better approaches right here. I'm only keeping it here for historical purposes.

Although the documentation poorly describes the strtotime function, @rjmunro correctly addressed the issue in his comment: it's in ISO format date "YYYY-MM-DD".

Also, even though my Date_Converter function might still work, I'd like to warn that there may be imprecise statements below, so please do disregard them.

The most voted answer is actually incorrect!

The PHP strtotime manual here states that "The function expects to be given a string containing an English date format". What it actually means is that it expects an American US date format, such as "m-d-Y" or "m/d/Y".

That means that a date provided as "Y-m-d" may get misinterpreted by strtotime. You should provide the date in the expected format.

I wrote a little function to return dates in several formats. Use and modify at will. If anyone does turn that into a class, I'd be glad if that would be shared.

function Date_Converter($date, $locale = "br") {

    # Exception
    if (is_null($date))
        $date = date("m/d/Y H:i:s");

    # Let's go ahead and get a string date in case we've
    # been given a Unix Time Stamp
    if ($locale == "unix")
        $date = date("m/d/Y H:i:s", $date);

    # Separate Date from Time
    $date = explode(" ", $date);

    if ($locale == "br") {
        # Separate d/m/Y from Date
        $date[0] = explode("/", $date[0]);
        # Rearrange Date into m/d/Y
        $date[0] = $date[0][1] . "/" . $date[0][0] . "/" . $date[0][2];
    }

    # Return date in all formats
        # US
        $Return["datetime"]["us"] = implode(" ", $date);
        $Return["date"]["us"]     = $date[0];

        # Universal
        $Return["time"]           = $date[1];
        $Return["unix_datetime"]  = strtotime($Return["datetime"]["us"]);
        $Return["unix_date"]      = strtotime($Return["date"]["us"]);
        $Return["getdate"]        = getdate($Return["unix_datetime"]);

        # BR
        $Return["datetime"]["br"] = date("d/m/Y H:i:s", $Return["unix_datetime"]);
        $Return["date"]["br"]     = date("d/m/Y", $Return["unix_date"]);

    # Return
    return $Return;

} # End Function
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Igor Donin
  • 412
  • 1
  • 8
  • 15
  • 2
    Reading on, I like Ceiroa fix on it. That's way easier than exploding/imploding the date. – Igor Donin Aug 07 '12 at 14:48
  • 3
    The top answer is not incorrect. PHP does the right thing with an ISO format date "YYYY-MM-DD". It cannot misinterpret it as a US date, because it has 4 digits at the start, and it uses - not / as a separator. ISO dates were carefully designed to not be confusable with other formats. – rjmunro Mar 04 '14 at 11:19
9

You can try the strftime() function. Simple example: strftime($time, '%d %m %Y');

Marty
  • 146
  • 1
  • 13
Sinan
  • 5,819
  • 11
  • 39
  • 66
9

In PHP any date can be converted into the required date format using different scenarios for example to change any date format into Day, Date Month Year

$newdate = date("D, d M Y", strtotime($date));

It will show date in the following very well format

Mon, 16 Nov 2020

Hassan Qasim
  • 463
  • 5
  • 5
  • 1
    And if you have time as well in your existing date format for example if you have datetime format of SQL 2020-11-11 22:00:00 you can convert this into the required date format using the following – Hassan Qasim Nov 19 '20 at 07:01
  • 1
    $newdateformat = date("D, d M Y H:i:s", strtotime($oldateformat)); – Hassan Qasim Nov 19 '20 at 07:01
7

Given below is PHP code to generate tomorrow's date using mktime() and change its format to dd/mm/yyyy format and then print it using echo.

$tomorrow = mktime(0, 0, 0, date("m"), date("d") + 1, date("Y"));
echo date("d", $tomorrow) . "/" . date("m", $tomorrow). "/" . date("Y", $tomorrow);
Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Vishnu
  • 71
  • 1
  • 1
7

Use this function to convert from any format to any format

function reformatDate($date, $from_format = 'd/m/Y', $to_format = 'Y-m-d') {
    $date_aux = date_create_from_format($from_format, $date);
    return date_format($date_aux,$to_format);
}
Juan Girini
  • 1,150
  • 2
  • 16
  • 31
6
date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));
kamal pal
  • 4,187
  • 5
  • 25
  • 40
AbdulBasit
  • 1,269
  • 11
  • 19
3
function dateFormat($date)
{
    $m = preg_replace('/[^0-9]/', '', $date);
    if (preg_match_all('/\d{2}+/', $m, $r)) {
        $r = reset($r);
        if (count($r) == 4) {
            if ($r[2] <= 12 && $r[3] <= 31) return "$r[0]$r[1]-$r[2]-$r[3]"; // Y-m-d
            if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$r[2]$r[3]-$r[1]-$r[0]"; // d-m-Y
            if ($r[0] <= 12 && $r[1] <= 31) return "$r[2]$r[3]-$r[0]-$r[1]"; // m-d-Y
            if ($r[2] <= 31 && $r[3] <= 12) return "$r[0]$r[1]-$r[3]-$r[2]"; //Y-m-d
        }

        $y = $r[2] >= 0 && $r[2] <= date('y') ? date('y') . $r[2] : (date('y') - 1) . $r[2];
        if ($r[0] <= 31 && $r[1] != 0 && $r[1] <= 12) return "$y-$r[1]-$r[0]"; // d-m-y
    }
}

var_dump(dateFormat('31/01/00')); // return 2000-01-31
var_dump(dateFormat('31/01/2000')); // return 2000-01-31
var_dump(dateFormat('01-31-2000')); // return 2000-01-31
var_dump(dateFormat('2000-31-01')); // return 2000-01-31
var_dump(dateFormat('20003101')); // return 2000-01-31
  • Try 2001-31-12 (Y-d-m). I'm sure your code would output 3112-01-20 (something like. md-y-y) which is obviously wrong. Second if case. – Sebi2020 Nov 20 '20 at 20:30
1

For this specific conversion we can also use a format string.

$new = vsprintf('%3$s-%2$s-%1$s', explode('-', $old));

Obviously this won't work for many other date format conversions, but since we're just rearranging substrings in this case, this is another possible way to do it.

Don't Panic
  • 41,125
  • 10
  • 61
  • 80
1

Simple way Use strtotime() and date():

$original_dateTime = "2019-05-11 17:02:07"; #This may be database datetime
$newDate = date("d-m-Y", strtotime($original_dateTime));

With time

$newDate = date("d-m-Y h:i:s a", strtotime($original_dateTime));
Sani Kamal
  • 1,208
  • 16
  • 26
1

You can change the format using the date() and the strtotime().

$date = '9/18/2019';

echo date('d-m-y',strtotime($date));

Result:

18-09-19

We can change the format by changing the ( d-m-y ).

Varun P V
  • 1,092
  • 1
  • 12
  • 30
1

Use date_create and date_format

Try this.

function formatDate($input, $output){
  $inputdate = date_create($input);
  $output = date_format($inputdate, $output);
  return $output;
}
Quatban Taco
  • 310
  • 1
  • 15