Home > Backend Development > PHP Tutorial > How Can I Convert a String to a Date or DateTime Object in PHP?

How Can I Convert a String to a Date or DateTime Object in PHP?

DDD
Release: 2024-12-28 08:55:10
Original
999 people have browsed it

How Can I Convert a String to a Date or DateTime Object in PHP?

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);
Copy after login

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
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template