[php] Convert a date format in PHP

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?

This question is related to php date formatting

The answer is


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


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

date('m/d/Y h:i:s a',strtotime($val['EventDateTime']));

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


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

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

Use date_create and date_format

Try this.

function formatDate($input, $output){
  $inputdate = date_create($input);
  $output = date_format($inputdate, $output);
  return $output;
}

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.


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


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);
}

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


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


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');

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

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

$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));

Use:

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

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


Examples related to php

I am receiving warning in Facebook Application using PHP SDK Pass PDO prepared statement to variables Parse error: syntax error, unexpected [ Preg_match backtrack error Removing "http://" from a string How do I hide the PHP explode delimiter from submitted form results? Problems with installation of Google App Engine SDK for php in OS X Laravel 4 with Sentry 2 add user to a group on Registration php & mysql query not echoing in html with tags? How do I show a message in the foreach loop?

Examples related to date

How do I format {{$timestamp}} as MM/DD/YYYY in Postman? iOS Swift - Get the Current Local Time and Date Timestamp Typescript Date Type? how to convert current date to YYYY-MM-DD format with angular 2 SQL Server date format yyyymmdd Date to milliseconds and back to date in Swift Check if date is a valid one change the date format in laravel view page Moment js get first and last day of current month How can I convert a date into an integer?

Examples related to formatting

How to add empty spaces into MD markdown readme on GitHub? VBA: Convert Text to Number How to change indentation in Visual Studio Code? How do you change the formatting options in Visual Studio Code? (Excel) Conditional Formatting based on Adjacent Cell Value 80-characters / right margin line in Sublime Text 3 Format certain floating dataframe columns into percentage in pandas Format JavaScript date as yyyy-mm-dd AngularJS format JSON string output converting multiple columns from character to numeric format in r