Home > Backend Development > PHP Tutorial > How to Convert Date Formats in PHP?

How to Convert Date Formats in PHP?

DDD
Release: 2024-12-21 06:17:16
Original
526 people have browsed it

How to Convert Date Formats in PHP?

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

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!

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