将日期时间格式更改为 Y-m-d,但日期时间类似于 7/12/17 6:20:39 pm

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

编辑:

我需要将此日期时间从 dd/mm/yy H:i:s 格式更改为 Y-m-d H:i:s 格式。

这适用于 PHP 或 CodeIgniter 项目。


我从其他报告中获取了一些格式不正确的数据。

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

如果我得到使用第一种格式日期的示例。

$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));

它的打印结果:2007-12-17 12:15:23这是一个错误的结果。

d F Y 日期打印 17 December 2007 但它应该是 07 December 2017


通常我们可以这样更改日期:

$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.

试试这个

$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

您可以使用 DateTimecreateFromFormat 方法 - 指定输入日期的格式,然后按照您希望的方式格式化输出 - 例如:

$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

对于输入日期戳中的 2 位数年份,而不是大写 Y 小写 y 应该匹配。

$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