himanshoo
himanshoo

Reputation: 21

Date array element to PHP array variable

I had datepicker element in HTML code ( multiple datepicker ) from for loop (data from database)

It display fine and let user choose different dates for different product. on submit, assign these dates into php variable through post.

But the element remains string not dates. How to change string to date in 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");
}  

Upvotes: 0

Views: 1369

Answers (1)

marcell
marcell

Reputation: 1528

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

Upvotes: 1

Related Questions