Verify time zone is correct.
Mar 2, 2018
11
Level 3
Carbon wrong date difference calculations
I have two dates
// get date from the database column created_at
$dt = \Carbon\Carbon::parse( $message->created_at );
// get today
$today = \Carbon\Carbon::today();
// counting difference
if( \Carbon\Carbon::parse( $message->created_at )->diffInDays( \Carbon\Carbon::today()) == 7 ){
return 'one week';
}
Bad when the $dt = 22.2.2018 and $today is 2.3.2018, Carbon count 7 days and return one week but, difference in real is 8 days. How compare two dates only via dates, without timestamp but create from created_at what is the timestamp ... ?
Level 122
difference is 7 days and xx hours not 8 days, and it probably depends what time of day your created_at is.
By the way, created_at is already an instance of Carbon.
In Tinker;
>>> $dt=Carbon\Carbon::parse('2018-02-22 00:00:00')
=> Carbon\Carbon @1519257600 {#821
date: 2018-02-22 00:00:00.0 UTC (+00:00),
}
>>> $dt->diffInDays()
=> 8
>>> $dt=Carbon\Carbon::parse('2018-02-22 23:00:00')
=> Carbon\Carbon @1519340400 {#822
date: 2018-02-22 23:00:00.0 UTC (+00:00),
}
>>> $dt->diffInDays()
=> 7
>>>
its 20:40 when I ran this
You can clear the time from a carbon timestamp with StartOfDay
>>> $dt=Carbon\Carbon::parse('2018-02-22 23:00:00')
=> Carbon\Carbon @1519340400 {#809
date: 2018-02-22 23:00:00.0 UTC (+00:00),
}
>>> $dt->startOfDay()->diffInDays()
=> 8
By the way, if you don't provide a timestamp to diffInDays then it assumes now()
2 likes
Please or to participate in this conversation.