PHP returned MongoDB Date to HTML Form Hidden field

A query returns objects, which I then want to loop through to create HTML content. I have a problem converting / using MongoDB BSON Date items…

I have tried:

<input type="hidden" id="roundDate" name="roundDate" value="<?php echo $round['roundDate']->toString(); ?>">

I can display the same field on the page (literally the line above in my PHP source code):

<?php echo $round['roundDate']->format("d M Y"); ?>

Essentially, I am using this structure to pass it through to the next page with an HTML form, via $_POST, which is then stored in $_SESSION for any further access / use.

Hope someone can correct my ways or spot the error!

What type is $round['roundDate']? I’m asking because the MongoDB\BSON\UTCDateTime class does not have a toString method, which is what your first call uses. The second call to format makes me think that $round['roundDate'] would be a DateTime instance retrieved using the toDateTime method in our BSON class. If so, using format with the W3C format string should do the trick:

<input type="hidden" id="roundDate" name="roundDate" value="<?php echo $round['roundDate']->format(\DateTimeInterface::W3C); ?>">

Thanks @Andreas_Braun

At the top of my PHP page, I call out to a separate function for the MongoDB query. This function retrieves the query as a cursor, then loops through the cursor, with sub-loops for embedded arrays within the cursor. This was done specifically so that all of the stored variables were converted to PHP-native data types, such as this DateTime. Here is the conversion of this to a PHP DateTime object:

$x = 0;
foreach ($cursor as $comp) {
  
  $y = 0;
  foreach ($comp['compRounds'] as $round) {
    ..
    $comps[$x]['compRounds'][$y]['roundDate'] = $round['roundDate']->toDateTime();
    
    $z = 0;
    foreach ($round['courses'] as $course) {
      ..
 
      $z++;
    }
    $y++;
  }
  $x++;
}

Is this a correct pattern / way of processing?

My requirement though is to allow me to save this same date into another collection, so its embedded there. So if I convert 1 way, I expect I will need to reverse it before performing the MongoDB insert command?

The driver will convert them back then write the BSON objects to the database. I’d suggest either using an ODM that takes care of this mapping for you, or always assume to receive BSON instances and work with those (e.g. call toDateTime() on it, then format the date).