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
Release: 2024-12-29 14:43:10
Original
378 people have browsed it

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

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'));
Copy after login
  1. Convert the timestamp to a DateTime object:
$dateTime = new DateTime();
$dateTime->setTimestamp($timestamp);
Copy after login
  1. Format the DateTime object in the desired format:
$newFormat = $dateTime->format('Y-m-d');
Copy after login

This will result in the following formatted string:

2003-10-16
Copy after login

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!

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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template