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

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

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 09:56:10750browse

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

Converting a String to Date and DateTime

A PHP string in the format of mm-dd-YYYY (e.g., 10-16-2003) can be converted to a Date and DateTime using the following steps:

Converting to Date:

  • Use the strtotime() function to convert the string to a Unix timestamp:
$time = strtotime('10/16/2003');
  • Convert the timestamp back to a Date using date('Y-m-d'):
$date = date('Y-m-d', $time);

echo $date; // 2003-10-16

Converting to DateTime:

  • Alternatively, you can use DateTime::createFromFormat() to create a DateTime object:
$dateTime = DateTime::createFromFormat('m/d/Y', '10/16/2003');

echo $dateTime->format('Y-m-d'); // 2003-10-16

Note:

  • There is a difference between using forward slash / and hyphen - in the strtotime() function. Follow the rules specified in the PHP documentation to avoid ambiguity.
  • For maximum accuracy and compatibility, consider using ISO 8601 (YYYY-MM-DD) date format or DateTime::createFromFormat() when possible.

The above is the detailed content of How Can I Convert a String to a Date and DateTime Object in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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