Home >Backend Development >PHP Tutorial >How to Convert mm-dd-YYYY Strings to YYYY-mm-dd Dates and DateTimes in PHP?
Converting a String to Date and DateTime
Converting a string in the mm-dd-YYYY format to a Date or DateTime object in the YYYY-mm-dd format is a common task in PHP development. Here's how you can achieve this:
Converting to Date:
The built-in strtotime() function can be used to convert the string to a PHP timestamp, which is a numerical representation of the date. From there, you can use the date() function with the 'Y-m-d' format to convert the timestamp back to a Date string:
$time = strtotime('10-16-2003'); $newFormat = date('Y-m-d', $time); echo $newFormat; // Output: 2003-10-16
Converting to DateTime:
To convert the string to a DateTime object, you can use DateTime::createFromFormat(), specifying the original format and then assigning the Y-m-d format:
$datetime = DateTime::createFromFormat('m-d-Y', '10-16-2003'); $datetime->format('Y-m-d'); // Output: 2003-10-16
Note:
Be cautious when using the strtotime() function with dates in the mm-dd-YYYY format, as ambiguity may arise. The function assumes the American m/d/y format if a slash (/) is used as the separator, while it assumes the European d-m-y format if a dash (-) or dot (.) is used. For clarity and to avoid potential issues, it's recommended to use the DateTime::createFromFormat() function when possible.
The above is the detailed content of How to Convert mm-dd-YYYY Strings to YYYY-mm-dd Dates and DateTimes in PHP?. For more information, please follow other related articles on the PHP Chinese website!