Converting Strings to Date and DateTime
When working with PHP strings representing dates, it's often necessary to convert them to the appropriate PHP data types, Date and DateTime, for further processing. Consider a PHP string in the format mm-dd-YYYY, such as "10-16-2003."
Converting to Date
A Date object encapsulates the date sans time information. To convert a string date to a Date, we can use the strtotime() function:
$date = strtotime('10-16-2003'); $dateObject = new Date($date);
Now, the $dateObject represents the date "2003-10-16."
Converting to DateTime
A DateTime object includes both date and time information. To convert a string date to a DateTime, we can use the same strtotime() function:
$dateTime = strtotime('10-16-2003'); $dateTimeObject = new DateTime($dateTime);
The resulting $dateTimeObject represents the DateTime "2003-10-16 00:00:00."
Note on Formatting
When using the strtotime() function, pay attention to the date formatting. Using forward slash (/) separates components in American (m/d/y) format, while hyphen (-) or dot (.) denotes European (d-m-y) format.
However, to avoid ambiguity, consider using ISO 8601 (YYYY-MM-DD) or the DateTime::createFromFormat() function when possible.
The above is the detailed content of How Can I Convert PHP String Dates to Date and DateTime Objects?. For more information, please follow other related articles on the PHP Chinese website!