Converting Date Formats in PHP
Question:
How can one convert one date format to another in PHP? For instance, converting the format 'y-m-d-h-i-s' to 'Y-m-d H:i:s'.
Answer:
PHP 5.3 and Up:
For PHP versions 5.3 and above, the DateTime::createFromFormat method can be employed. It allows for specifying a precise mask (the date() syntax) to parse incoming date strings.
PHP 5.2 and Lower:
In PHP versions 5.2 and below, manual parsing is necessary. Using substr(), extract date elements (year, month, day, hour, minute, second) and pass them to mktime(), which will generate a timestamp.
Alternative Solution:
To avoid manual parsing, consider utilizing a format that strftime() can interpret. strftime() supports a wide array of date inputs. For example, the following would work:
$old_date = date('l, F d y h:i:s'); // returns Saturday, January 30 10 02:06:34 $old_date_timestamp = strtotime($old_date); $new_date = date('Y-m-d H:i:s', $old_date_timestamp);
The above is the detailed content of How to Convert Date Formats in PHP?. For more information, please follow other related articles on the PHP Chinese website!