Home >Backend Development >PHP Tutorial >How to Convert a String Date to PHP Date and DateTime Objects?
Converting Date and Time Representations
Converting a string representation of a date (e.g., "10-16-2003" in mm-dd-YYYY format) to both a basic Date and a more detailed DateTime can be accomplished in PHP.
Converting to Date:
To convert the string to a PHP Date object (preserving the original format), use the following code:
$date = new DateTime('10-16-2003');
Converting to DateTime:
To convert the Date object to a DateTime object and format it in YYYY-mm-dd format, perform the following steps:
$timestamp = strtotime($date->format('m/d/Y'));
$dateTime = new DateTime(); $dateTime->setTimestamp($timestamp);
$newFormat = $dateTime->format('Y-m-d');
This will result in the following formatted string:
2003-10-16
Additional Note:
When using the strtotime() function, pay attention to the separator used between the date components. A slash (/) indicates the American m/d/y format, while a hyphen (-) or dot (.) indicates the European d-m-y format. To avoid ambiguity, it is recommended to use ISO 8601 (YYYY-MM-DD) dates or the DateTime::createFromFormat() method for parsing dates.
The above is the detailed content of How to Convert a String Date to PHP Date and DateTime Objects?. For more information, please follow other related articles on the PHP Chinese website!