Home >Backend Development >PHP Tutorial >How to Convert a String Date to PHP Date and DateTime Objects?

How to Convert a String Date to PHP Date and DateTime Objects?

Linda Hamilton
Linda HamiltonOriginal
2024-12-29 14:43:10373browse

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:

  1. Create a timestamp using strtotime():
$timestamp = strtotime($date->format('m/d/Y'));
  1. Convert the timestamp to a DateTime object:
$dateTime = new DateTime();
$dateTime->setTimestamp($timestamp);
  1. Format the DateTime object in the desired format:
$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!

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
Previous article:PHP, Classes and ObjectsNext article:PHP, Classes and Objects