days between two dates in laravel Hello
I want calculate days between two dates in laravel
End date is currant date Start date I have in DB like this format 2021-03-01 04:03:00
How can I do what $date1 see only Y-m-d (2021-03-01)
function dateDiffInDays($date1, $date2)
{
$diff = strtotime($date2) - strtotime($date1);
return abs(round($diff / 86400));
}
// Start date
$date1 = "2021-03-01 04:03:00";
// End date
$date2 = date('Y-m-d');
$dateDiff = dateDiffInDays($date1, $date2);
and how I can send this calculate day index function
public function index()
{
$products = Product::all();
return view('products.index', [
'products'=>$products,
]);
}
$date = "2021-03-01 04:03:00";
$diff = now()->diffInDays(Carbon::parse($date));
Docs: https://carbon.nesbot.com/docs/#api-difference
Of course when you work with Eloquent then your date will be automatically carbon instance, for example
$diff = now()->diffInDays($model->created_at);
In blade I have
{{$car->buy_date}}
And I want show day between buy date and date now
And what is the problem?
Just use what I posted above
{{ now()->diffInDays($car->buy_date) }}
{{ now()->diffInDays($car->buy_date) }} using only this time no and buy date using format Y-m-d H:i:s ,
I want pars and and then calculate between Y-m-d not use H:i:s
You probably get the same number of days.
{{ today()->diffInDays($car->buy_date->toDateString()) }}
Start reading a documentation.
Now I don't get same same number of day number.
Using {{ now()->diffInDays($car->buy_date) }}
for ex. if buy date I have 2021-05-07 00:00:00 day = 19
if 2021-05-07 23:00:00 day = 18
p.s.
using {{ today()->diffInDays($car->buy_date->toDateString()) }}
error Call to a member function toDateString() on string
I check doc but can not find how get from $car->buy_date date form Y m d
try this but not works
$car->buy_date->format('Y-m-d')
{{ now()->diffInDays(Carbon\Carbon::parse($car->buy_date)) }}
but as suggested you can cast the date to an instance of Carbon within the eloquent model and then not need to to do it here
no. now() is a helper that returns a carbon instance
now showing date like 2021-05-07 23:00:00
with what code? Not with what you have been shown, thats for sure.
if now() says its the 7th May then your clock is wrong or you are in nepal
some strange calendar.
actually today in nepal is Jestha 13 2078 (apparently)
$startDate = Carbon::parse($request['startDate']);
$endDate = Carbon::parse($request['endDate']);
$diff = $endDate->diffInDays($startDate);
Please sign in or create an account to participate in this conversation.