How can the createFromFormat function in PHP's DateTime class be optimized for accurate timestamp retrieval?

When using the createFromFormat function in PHP's DateTime class to parse a date string into a DateTime object, it is important to provide the correct format string to ensure accurate timestamp retrieval. To optimize this function, make sure to use the correct format characters that match the date string being parsed. This will help prevent any errors or incorrect timestamps.

$dateString = "2022-12-31 23:59:59";
$format = "Y-m-d H:i:s";
$dateTime = DateTime::createFromFormat($format, $dateString);

if ($dateTime !== false) {
    echo $dateTime->getTimestamp();
} else {
    echo "Failed to parse date string.";
}