0

I want to convert the string date to following format 'Y-m-d' from multiple date format like for example

12-3-17, 12-3-2017, 12.3.17, 12.3.2017, 12.03.17, 12/3/17

$ymd = DateTime::createFromFormat('m-d-Y', '10-16-2003')->format('Y-m-d');

The closest solution that i got so far is from the following article read the article here

is there a better solution, considering the fact that the input date string may be in unknown format ?

Dan
  • 69
  • 1
  • 8
  • Using DateTime, DateInterval & DateTimeZone classes is the best solution imo. And if you work a lot with dates you can consider this component : https://github.com/briannesbitt/Carbon (it has usefull methods) – Elbarto Mar 31 '17 at 09:54

1 Answers1

0

I hope this might help you. In dateFormat() function you can assign different type of valid format.

function dateFormat() {
    $date_format['d.m.Y'] = 'd.m.Y';
    $date_format['d.m.y'] = 'd.m.y';
    $date_format['d-m-Y'] = 'd-m-Y';
    $date_format['d-m-y'] = 'd-m-y';
    $date_format['d/m/Y'] = 'd/m/Y';
    $date_format['d/m/y'] = 'd/m/y';

    return $date_format;
}

After that you use this function as below code

$source = '2017-03-31';
$date = new DateTime($source);
$date_format = dateFormat();
foreach($date_format as $k => $v) {
    $date_list[] = $date->format($k); 
}
print_r($date_list);
exit;

Output:-

Array
(
    [0] => 31.03.2017
    [1] => 31.03.17
    [2] => 31-03-2017
    [3] => 31-03-17
    [4] => 31/03/2017
    [5] => 31/03/17
)

Live Demo

sandip kakade
  • 1,346
  • 5
  • 23
  • 49