Laracast13's avatar

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

  1. 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);
  1. and how I can send this calculate day index function
   public function index()
    {
        
        $products = Product::all();     
      
 
        return view('products.index', [
            'products'=>$products, 
            ]);
    }
0 likes
18 replies
MichalOravec's avatar
$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);
1 like
Laracast13's avatar

In blade I have {{$car->buy_date}}

And I want show day between buy date and date now

MichalOravec's avatar

And what is the problem?

Just use what I posted above

 {{ now()->diffInDays($car->buy_date) }}
1 like
Laracast13's avatar

{{ 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

MichalOravec's avatar

You probably get the same number of days.

 {{ today()->diffInDays($car->buy_date->toDateString()) }}

Start reading a documentation.

Laracast13's avatar

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

Laracast13's avatar

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')

Snapey's avatar
 {{ 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

Snapey's avatar

no. now() is a helper that returns a carbon instance

Snapey's avatar

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

1 like
Snapey's avatar

some strange calendar.

actually today in nepal is Jestha 13 2078 (apparently)

Abdullah_Iftikhar's avatar

$startDate = Carbon::parse($request['startDate']); $endDate = Carbon::parse($request['endDate']); $diff = $endDate->diffInDays($startDate);

1 like

Please or to participate in this conversation.