Home >Backend Development >PHP Tutorial >How Can I Convert a 'y-m-d-h-i-s' Date String to 'Y-m-d H:i:s' in PHP?

How Can I Convert a 'y-m-d-h-i-s' Date String to 'Y-m-d H:i:s' in PHP?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-24 18:32:34560browse

How Can I Convert a 'y-m-d-h-i-s' Date String to 'Y-m-d H:i:s' in PHP?

Converting Date Formats in PHP

You may encounter situations where you need to transform dates from one format to another in PHP. While PHP offers several functions for date manipulation, it's essential to understand the process and potential pitfalls.

Consider this scenario: You have a date in the format 'y-m-d-h-i-s', and you want to convert it to the 'Y-m-d H:i:s' format. Typically, you would use strtotime() to convert the string to a timestamp and then pass it to date(). However, in your case, strtotime() returns false, leaving you with the incorrect date of '1970-01-01 00:00:00'.

The issue lies in the format of the input string. strtotime() expects a valid timestamp or a string in a format it recognizes. Unfortunately, 'y-m-d-h-i-s' is not one of those recognized formats.

Solutions

PHP 5.3 and Up

For PHP 5.3 and later, the recommended solution is to use DateTime::createFromFormat(). This function allows you to specify a precise mask using the date() syntax to parse incoming string dates. For your case, the code would look like this:

$datetime = DateTime::createFromFormat('y-m-d-h-i-s', $old_date);
$new_date = $datetime->format('Y-m-d H:i:s');

PHP 5.2 and Lower

In PHP 5.2 and lower, you придется manually parse the elements (year, month, day, hour, minute, second) using substr() and feed the results to mktime(), which will generate a timestamp.

However, this approach is more cumbersome. It's better to use a different format that strftime() can understand, which supports various date input formats. For example, this code works:

$old_date = date('l, F d y h:i:s');                
$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 Can I Convert a 'y-m-d-h-i-s' Date String to 'Y-m-d H:i:s' in PHP?. 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