php – Getting datetime object from a string given by a user-ThrowExceptions

Exception or error:

The problem is to get datetime object from a string when the user provide date in any of the following format(dd-mm-yyyy , yyyy-mm-dd) my result should be in (yyyy-mm-dd). My function is as follows as:

public function dateOfBirth($date){
    $date_format = strtotime($date);
    $result = new \DateTime('@'.$date_format);
}

It successfully returns date as (yyyy-mm-dd) when the date is in (yyyy-mm-dd) format but returns the following error when user provides date in(dd-mm-yyyy) format

DateTime::__construct(): Failed to parse time string (@) at position 0 (@): Unexpected character

I need date return in (yyyy-mm-dd) format when user enters any of the above format

How to solve:
$one = new \DateTime('2018-08-12');
$two = new \DateTime('12-08-2018');
var_dump($one, $two);

in php 5.6+ both a valid DateTime objects. So now you can return it in desired format

$one->format('Y-m-d'); // echoes 2018-08-12
$two->format('Y-m-d'); // echoes 2018-08-12

Answer:

Try this code:

function getFormattedDate($date)
{
    $dateObj = new DateTime($date);

    return $dateObj->format('Y-m-d');
}

call the function:

print_r(getFormattedDate('23-12-2017'));
print_r(getFormattedDate('2016-02-20'));
print_r(getFormattedDate('15-05-2018'));

Answer:

This code works for me, Thank you all for your response,

public function dateOfBirth($date){
    $date_format = strtotime($date);
    $result = (new \DateTime())->setTimestamp($date_format);
}

Answer:

You can use a combination of date() and DateTime as below;

public function formatDate($date){
    $dateObj = new DateTime(date($date));

    return $dateObj->format('Y-m-d');
}

Answer:

    $in1 = '2018-08-20';
    $in2 = '20-08-2018';
    print_r(userDate($in1)); // 2018-08-20
    print_r(userDate($in2)); // 2018-08-20
    print_r(userDate(time())); // 2018-08-20

    function userDate($date)
    {
        if ($result = \DateTime::createFromFormat('Y-m-d', $date)) return $result->format('Y-m-d');
        if ($result = \DateTime::createFromFormat('d-m-Y', $date)) return $result->format('Y-m-d');
        // ...
        $dt = new \DateTime();
        if ($result = $dt->setTimestamp($date)) return $result->format('Y-m-d');
        return null;
    }

Leave a Reply

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