首页 > 解决方案 > 日期数组元素到 PHP 数组变量

问题描述

我有来自 for 循环的 HTML 代码(多个 datepicker)中的 datepicker 元素(来自数据库的数据)

它显示良好,让用户为不同的产品选择不同的日期。在提交时,通过 post 将这些日期分配给 php 变量。

但是该元素仍然是字符串而不是日期。如何在php中将字符串更改为日期?

<td colspan=2>
    <input type="text" 
           name="expirydate[]" 
           id="expirydate<? echo $SNO;?>" 
           autocomplete="off"  
           class="expirydate" 
           value="<? $DateToday=date('Y-m-d');
                     $ShowDate1 = explode("-", $DateToday);
                     $ShowDate2 = "$ShowDate1[2]/$ShowDate1[1]/$ShowDate1[0]";
                     echo $ShowDate2; ?>"
    />
</td>
$(function(){
        $('.expirydate').datepicker({ minDate: 0 }); 
}); 
$expirydate = $_POST["expirydate"];

for ($x=0; $x<=$TotalCount-1; $x++)
    {
    $expirydate1 = $expirydate[$x];
    $n1 = explode("/", $expirydate1);
    echo $n1[0] . "--" . $n1[1] . "--" . $n1[2] . "<br>";
    $n2 = "$n1[2]-$n1[1]-$n1[0]";
    $n22 = date_create($n2);
    $n3 = date_format($n22,"Y/m/d H:i:s");
}  

标签: phparraysdate

解决方案


According your code above $ShowDate2 is in the format of d/m/Y. Using DateTime::createFromFormat you can parse the date string into a DateTime object.

$date = DateTime::createFromFormat('d/m/Y', '27/11/2019');

If you want it formatted just use the format method on it: $date->format('Y-m-d').

If your $expirydate is an array of dates in the mentioned d/m/Y format, you can do the following:

$expirydate = [ '27/11/2019', '26/11/2019', '25/11/2019'];
$dates = array_map(function($date) {
    return DateTime::createFromFormat('d/m/Y', $date);
}, $expirydate);

推荐阅读