如何在PHP中将数组转换为日期格式?

时间:2019-05-07 21:52:35

标签: php datetime

我在PHP中得到的数组为:

Array
(
    [1] => 2019
    [2] => 5
    [3] => 7
    [4] => 0
)

其中[1]始终为年份,[2]始终为月份,[3]始终为日期。

如何将该数组转换为date("Y-m-d")格式?

5 个答案:

答案 0 :(得分:1)

您可以使用DateTime

$timeArray = [2019,5,7,0];
$dateTime = new DateTime(printf( "%d-%d-%d", $timeArray[0],$timeArray[1],$timeArray[2] ));
echo $dateTime->format('Y-m-d'); // output: 2019-05-07

答案 1 :(得分:1)

这样做

$arr = array( '2019', '5', '7', '0' );
echo date('Y-m-d',strtotime("$arr[0]/$arr[1]/$arr[2]"));

答案 2 :(得分:1)

尽管可以将这些值连接成一个字符串,然后让PHP将字符串解析为Y-m-d格式,但我个人认为mktime()是更好的解决方案:

echo date("Y-m-d", mktime(0, 0, 0, $arr[2], $arr[3], $arr[1]));
// 2019-05-07

这消除了PHP意外地以错误的顺序解释日期和月份的风险。

答案 3 :(得分:1)

假设此数据输入:

$data = [null, 2019, 5, 7, 0];

使用DateTime

$dt = new DateTime(sprintf( "%04d-%02d-%02d", $data[1], $data[2], 
$data[3]));
echo $dt->format('Y-m-d') . "\n";

使用Sprintf

// use this if you really trust the data
$dt = sprintf( "%04d-%02d-%02d", $data[0], $data[1], $data[2]);
echo $dt . "\n";

使用碳

// Carbon is a fantastic Date and Time class -> https://carbon.nesbot.com/
$dt = \Carbon\Carbon::create($data[0], $data[1], $data[2], 0, 0, 0);
echo $dt->format('Y-m-d') . "\n";

答案 4 :(得分:-1)

您可以简单地使用concat并将它们连接到字符串中:

ALTER TRIGGER [dbo].[tr_TargetUserDel] ON [dbo].[TargetUser]
AFTER  INSERT
AS
BEGIN
  SET NOCOUNT ON;       
  INSERT INTO [dbo].[TargetUser]([UserId], [TargetId])
  SELECT UserId,
         TargetId
  FROM INSERTED;

  DELETE T
  FROM [dbo].[TargetUser] T INNER JOIN INSERTED TT
  ON T.TargetId = TT.TargetId 
     AND
     T.TargetUserId <> TT.TargetUserId;
  SET NOCOUNT OFF; 
END

输出

$arr = array(
    "1" => "2019",
    "2" => "5",
    "3" => "7",
    "4" => "0",
);

$datetime_format = $arr["1"] . "-" . $arr["2"] . "-" . $arr["3"];

var_dump($datetime_format);

如果您希望使用4-2-2格式,则可以使用:

string(8) "2019-5-7"

输出

$arr = array(
    "1" => "2019",
    "2" => "5",
    "3" => "7",
    "4" => "0",
);

$datetime_format = '';
foreach ($arr as $key => $value) {
    if ($key == "4") {break;}
    echo strlen($value);
    if (strlen($value) >= 2) {
        $datetime_format .= $value;
    } elseif (strlen($value) == 2) {
        $datetime_format .= $value;
    } elseif (strlen($value) == 1) {
        $datetime_format .= "0" . $value;
    } else {
        echo "Something is not right!";
    }
    if ($key <= "2") {$datetime_format .= '-';}
}

var_dump($datetime_format);