简体   繁体   中英

How to convert array to date format in PHP?

I am getting an array in PHP as:

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

where [1] is always the year, [2] is always the month and [3] is always the date.

How can I convert this array to date("Ymd") format?

Assuming this data input:

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

Using DateTime

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

Using Sprintf

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

Using Carbon

// 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";

you can use 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

Do it like this

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

Although it's possible to just concatenate those values into a string and then let PHP parse that string into the Ymd format, I personally think mktime() is the better solution:

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

This removes the risk of PHP accidentally interpreting the day and month in the wrong order.

You might simply use concat and join them into a string:

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

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

var_dump($datetime_format);

Output

string(8) "2019-5-7"

If you wish to have a 4-2-2 format, this might work:

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

Output

string(10) "2019-05-07"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM