如何调整数组中的日期格式


How to adjust a date format in an array?

这里,我只想从数组中获取日期。阵列为:

print_r($incomplete);
Output:
Array
(
    [0] => 2015-09-21 11:20:37
)

我想要下面的格式

Array
(
    [0] => 2015-09-21
)

我已经试过了,

echo date('Y-m-d',strtotime($incomplete));

日期转换代码有效。$incomplete中有一个数组,因此必须使用$incomplete[0]才能访问该值。简单的解决方案是:

$incomplete[0] = date('Y-m-d',strtotime($incomplete[0]));

现在您有了相同的数组数据,但没有时间。

strtotime将输入作为字符串。

echo date('Y-m-d',strtotime($incomplete[0]));

strtotime希望得到一个包含英文日期格式的字符串,并将尝试将该格式解析为Unix时间戳。您已经将array传递给了这个函数。还添加如下数组索引:

echo date('Y-m-d',strtotime($incomplete[0]));

日期转换不会直接用于数组。因此,您需要在代码中传递数组元素来代替数组:

echo date('Y-m-d',strtotime($incomplete[0]));

希望这会有所帮助,如果你需要进一步的帮助,请告诉我。

您可能希望将包含以下日期的数组的单元格作为目标:

echo date('Y-m-d',strtotime($incomplete[0]));

您可以从Y-m-d H:i:sdatetime转换为date。但是,您不能仅在数组上执行该代码。您需要获取特定的数组键值对。

示例

// Creating your array
$array = array(
    '0' => '2015-09-20 10:20:30'
);
// Get date from array and create DateTime Object
$date = new DateTime($array[0]);
// Change date format and output
$array[0] = $date->format('Y-m-d');

在阵列上

数组是将一个或多个类似类型的值存储在单个值中的数据结构。例如,如果你想存储100个数字,那么定义一个长度为100的数组就很容易了,而不是定义100个变量。

有三种不同类型的数组,每个数组值都使用称为数组索引的ID c进行访问。[…]

资源:

  • 阵列教程
  • PHP手册