Home > other >  Calculate the remaining days on view Laravel, negative days if date has passed
Calculate the remaining days on view Laravel, negative days if date has passed

Time:05-08

These are the values on my database, I just need to get the remaining days of each today:

SQL table

{{ \Carbon\Carbon::now()->diffInDays($patient->date_end) }}

CodePudding user response:

To get the difference between two date you could make use of carbon in following ways:

$start = Carbon::parse('2022-04-30');
$end = Carbon::parse('2022-05-06');
$diff = $start->diffInDays($end);

Above, code should give you the difference between this $start and $end date difference in days. Here, instead of static date 2022-04-30. You might have to pass it using object or array values. Something like $start = Carbon::parse($patient->date_start);

But, in case you are saying to find the difference between current date and date_end then you could do:

$end = Carbon::parse($patient->date_end);
{{ \Carbon\Carbon::now()->diffInDays($end) }}

This will give you the difference between and end date.

And, looking at the small details you have provided, it looks like you are not parsing the data. You might have to parse it first so that it could find the diff.

If you want to get negative values, you might have to pass false as the second parameter,diffInDays($patient->date_end, false). Other than this, sometimes still you might get incorrect values, and this could be because of timezone. Let's say you are in GMT -7, and on UTC its already a new date but in your timezone its still a previous day. On this case, you might see 0 day remaining, even if it is 2 days remaining according to your timezone.

On that case, you might have to pass timezone as well.

\Carbon\Carbon::now()->diffInDays($end,false)->timezone('America/New_York'));

CodePudding user response:

the problem solved but , im confused with the may 7 , which is the 3rd row should give me a negative value

If you want to get the negative values, you would need to pass false as the second parameter of the diffInDays function.

Carbon\Carbon::now()->diffInDays($patient->date_end, false)

The second parameter sets whether you want the absolute difference or not. Default is true, which returns absolute difference.

  • Related