Change datetime format to Y-m-d, but the datetime is like 7/12/17 6:20:39 pm [duplicate]

扶醉桌前 提交于 2019-12-14 04:26:48

问题


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



来源:https://stackoverflow.com/questions/48517435/change-datetime-format-to-y-m-d-but-the-datetime-is-like-7-12-17-62039-pm

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!