Converting String to Date and DateTime
In PHP, you may encounter a need to convert a string representing a date from a given format to Date and DateTime objects. Here's a comprehensive solution that demonstrates how to achieve this task effectively.
To convert a string in the mm-dd-YYYY format to a Date object, you can utilize PHP's built-in strtotime() function:
$dateString = '10-16-2003'; $dateTimestamp = strtotime($dateString); $date = new Date($dateTimestamp);
To further convert the Date object to a DateTime object using the YYYY-mm-dd format, employ the following approach:
$dateTime = new DateTime(); $dateTime->setTimestamp($date->getTimestamp()); $newFormat = $dateTime->format('Y-m-d'); echo $newFormat; // Output: 2003-10-16
Note that the difference between forward slash (/) and hyphen (-) in the strtotime() function is crucial. When using a forward slash, the American m/d/y format is assumed, while a hyphen or dot indicates the European d-m-y format.
To avoid potential ambiguities, consider using ISO 8601 (YYYY-MM-DD) dates or DateTime::createFromFormat() for more flexible and reliable conversions.
The above is the detailed content of How Can I Convert a String to a Date or DateTime Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!