$date_string = '2021-10-31'; $date = DateTime::createFromFormat('Y-m-d', $date_string); echo $date->format('Y-m-d'); // Output: 2021-10-31
$date_string = '31/10/2021 12:30:00'; $date = DateTime::createFromFormat('d/m/Y H:i:s', $date_string); echo $date->format('Y-m-d H:i:s'); // Output: 2021-10-31 12:30:00
$date_string = '20211031'; $date = DateTime::createFromFormat('Ymd', $date_string); echo $date->format('Y-m-d'); // Output: 2021-10-31The DateTime createFromFormat function is a part of the PHP DateTime class, which is a part of the PHP standard library.