Be part of JetBrains PHPverse 2026 on June 9 – a free online event bringing PHP devs worldwide together.

jesse_orange_newable's avatar

Working with date and time

I have a query scope called inDate that is meant to check the given start_datetime and check whether its newer than today i.e Carbon::today(), however I can't wrap my head around this.

I have a test:

/** @test */
public function it_knows_if_its_in_date_query_scope()
{
    $start = Carbon::now();
    $end = Carbon::now()->addDay();

    $eventInDate = factory(Event::class)->create([
        'date_not_available' => false,
        'start_datetime' => [
            'date' => $start->format('Y-m-d'),
            'time' => $start->format('H:i'),
        ],
        'finish_datetime' => [
            'date' => $end->format('Y-m-d'),
            'time' => $end->format('H:i'),
        ],
    ]);

    $eventsDueToHappen = Event::inDate()->get();

    $this->assertFalse($eventsDueToHappen->contains($eventInDate));
}


Now, the start_datetime of dueToHappen is the current time, which for me is 2020-08-06 16:59:00

The query scope looks like this:


public function scopeInDate($query)
{
    return $query->where('start_datetime', '>=', Carbon::today()->startOfDay()->toDateTimeString());
}

Dumping this outputs the following SQL:


"select * from `events` where `start_datetime` >= ? and `events`.`deleted_at` is null"
array:1 [
  0 => "2020-08-06 00:00:00"
]

How can this test be failing as 16:00 is older than 00:00

0 likes
2 replies
Nakov's avatar

@jesse_orange_newable but you are comparing a string to a date, you can try just using:

Carbon::today()->startOfDay()

without the ->toDateTimeString().

jesse_orange_newable's avatar

My bad, I forgot a part:


/**
 * Set the start date & time
 *
 * @param [type] $value
 *
 * @return void
 */
public function setStartDatetimeAttribute($value)
{
    $date = $value['date'] ?? null;
    $time = $value['time'] ?? '';

    if (!is_null($date)) {
        return $this->attributes['start_datetime'] = Carbon::parse($date . $time);
    }

    return $this->attributes['start_datetime'] = Carbon::now();
}

Please or to participate in this conversation.