Carbon: diff two datetime objects by dates only
Asked Answered
C

2

20

Assuming I have the following code:

$now = Carbon::now();
$dateTimeObject = Carbon::parse('2017-07-20 10:16:34');

how do I get the diff between the dates only, ignoring the time factor?

So, if $now is 2017-07-27 09:11:12, and the date in the $dateTimeObject is 2017-07-20 -- the difference would be 7.

I need it to make sure the results of a specific operation are being stored in the database only once per day.

Note:

I tried the diffInDays() method, but it returns 0 if the values are e.g. 2016-10-12 23:56:43 and 2016-10-13 02:01:53 - so, close to midnight and at night.

Connaught answered 27/7, 2017 at 19:24 Comment(0)
K
46

Do something like this:

$now = Carbon::now()->startOfDay();
$dateTimeObject = Carbon::parse('2017-07-20 10:16:34')->startOfDay();

And now use diffInDays().

Kling answered 27/7, 2017 at 19:51 Comment(2)
how to compare just date?Arbor
This IS comparing just date. startOfDay sets the time to 0:00:00Associative
B
5

Carbon::isSameDay method will check if the given date is in the same day as the instance. If null passed, compare to now (with the same timezone).

$dateTimeObject = Carbon::parse('2017-07-20 10:16:34');

$is_same = $dateTimeObject->isSameDay();
Bulrush answered 22/6, 2021 at 10:5 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.