Convert datetime field to date only

I have a list of events in a single file and currently parse them with ->toStructure().
One of the recurring fields is called event_dtstart. It’s a DateTime object (i.e. 2018-03-08 22:45 for example).
Now, I’m trying to list my events by date. I thus planned on plucking the field and extracting every single date, which then serves as a comparator in a ->filterBy() method.
However, such a datetime object does not match with a date, since the unix timestamp differs (i.e. 2018-03-08 10:30 is not equal to 2018-03-08 11:30).
Any ideas as to how I could convert my fields to a date-only format?


Yes, you can format the date:

$event->date('Y-m-d', 'event_dtstart')

You can then convert this to a UNIX timestamp without the hours again, in case you need it:

strtotime($event->date('Y-m-d', 'event_dtstart'))

Thanks for your reply. Please pardon my ignorance, but I’m at a loss as to how to use this with a field in a structure.

Currently, my code looks like this:

// get all events
$events = $section->events()->toStructure();

// parse dates
$dates = $events->pluck('event_dtstart', null, true);

// list all unique dates
foreach ($dates as $date) {
  echo $date;

Currently, $date is a DateTime object. I know how to echo the variable within the foreach loop. My goal however is to list all unique dates, which means that the DateTime to Date conversion has to happen at the ->plunk() level.

Thanks a lot!

There’s a much easier way to achieve this, using group():

$events = $section->events()->toStructure();
$groups = $events->group(function($event){
  return $event->date('Y-m-d', 'event_dtstart');
foreach($groups as $date => $group): ?>
  <h2><?= $date ?></h2>
  <?php foreach($group as $item): ?>
     <li><?= $item->title() ?></li>
  <?php  endforeach; ?>
<?php endforeach; ?>

My god, I overlooked group()! Thank you so much, it works flawlessly!