Change datetime format to Y-m-d, but the datetime

2019-09-20 16:10发布

问题:

This question already has an answer here:

  • Converting string to Date and DateTime 9 answers
  • Convert date format yyyy-mm-dd => dd-mm-yyyy 15 answers
  • Convert one date format into another in PHP 15 answers
  • Should I use the datetime or timestamp data type in MySQL? 37 answers

EDIT :

I need to change this datetime into Y-m-d H:i:s format from dd/mm/yy H:i:s format.

This is for PHP or CodeIgniter project.


I got some data from other report not formatted well.

datetime
7/12/17 12:15:23 pm (dd/mm/yy H:i:s) format
8/12/17 5:18:12 am
20/12/17 5:12:24 pm
21/12/17 12:17:37 pm

If I get example using 1st format date.

$example_date = "7/12/17 12:15:23 pm"; // d F Y : 07-December-2017 12:15:23
$format_date = $date("Y-m-d", strtotime($example_date));

Its printed : 2007-12-17 12:15:23 It's a wrong result.

In d F Y date it's printed 17 December 2007 but It's should be 07 December 2017.


Normally we can change date using like this :

$example_datetime = "13/12/2017 12:08:16 pm"; // (dd/mm/yy H:i:s) format
$format_date = date("Y-m-d H:i:s", strtotime($example_datetime));

Result from echo $format_date => 2017-12-13 12:08:16 is correct. If the year is 2017 and this is what I wanted to.

回答1:

You could use the DateTime and createFromFormat method - specifying the format of the input date and then formatting how you wish for output - ex:

$example_datetime = "13/12/2017 12:08:16 pm";
$date=DateTime::createFromFormat('d/m/Y H:i:s a', $example_datetime );

$output=$date->format('Y-m-d H:i:s');
echo $output; //  -> 2017-12-13 12:08:16

For a 2-digit year in the input datestamp, rather than the uppercase Y a lowercase y should match.

$example_datetime = "13/12/17 12:08:16 pm";
$date=DateTime::createFromFormat('d/m/y H:i:s a', $example_datetime );

$output=$date->format('Y-m-d H:i:s');
echo $output; //  -> 2017-12-13 12:08:16


回答2:

Try This

$example_datetime = "13/12/2017 12:08:16 pm"; // (dd/mm/yy H:i:s) format
$date = str_replace('/', '-', $example_datetime);
echo date("Y-m-d H:i:s", strtotime($date)); // Y-m-d H:i:s

Dates in the m/d/y or d-m-y formats are disambiguate by looking at the separator between the various components: if the separator is a slash (/), then the American m/d/y is assumed; whereas if the separator is a dash (-) or a dot (.), then the European d-m-y format is assumed. Check more here: http://php.net/manual/en/function.strtotime.php