0

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");
}  
5
  • <? is not PHP open tag. <?php is. Commented Nov 27, 2019 at 7:37
  • ok fine. but it is working. Commented Nov 27, 2019 at 7:39
  • 1
    Please post the value of $expirydate Commented Nov 27, 2019 at 7:49
  • $expirydate is an array and it gives dates as string....27/11/2019,28/11/2019,29/11/2019 likewise Commented Nov 27, 2019 at 8:22
  • What are you planning to do with the declared but not accessed $n3 variable in your script? Commented Nov 2, 2024 at 6:50

1 Answer 1

1

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);
Sign up to request clarification or add additional context in comments.

2 Comments

$expirydate is an array but of string type. it takes dates as string
@himanshoo then you can use the snippet above in order to parse the date strings into datetime object, the resulting $dates is an array of datetime objects.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.