user11636668
user11636668

Reputation:

how to convert any date to specific format in php?

I created a function where i pass different format of dates, I want to convert any date format to specific format that i defined.

function change_date_format($date)
{
    $date = date('Y-m-d', strtotime($date));
    return $date;
}

print_r(change_date_format('28/02/2012'));

This format of date return 1970-01-01

Upvotes: 1

Views: 44

Answers (1)

Death-is-the-real-truth
Death-is-the-real-truth

Reputation: 72299

What @Magnus Eriksson suggested is, to send format as a parameter and then use DateTime::createFromFormat()

<?php

function change_date_format($givenDate,$format)
{
    $date = date_create_from_format($format, $givenDate);
    echo date_format($date, 'Y-m-d');
}

print_r(change_date_format('08/02/2012','d/m/Y'));
echo PHP_EOL;
print_r(change_date_format('08/02/2012','m/d/Y'));

Output:- https://3v4l.org/SlNtA

Upvotes: 1

Related Questions