I am using laravel and carbon package.I have two date. Now I want to get date difference from my given date.
$start_Date='2016-06-02 18:00:13';
$end_Date='2016-06-06 18:00:13';
$start = Carbon::parse($start_Date);
$end = Carbon::parse($end_Date);
$now = Carbon::now();
$length = $start->diffInDays($now);
$lengthFromEnd = $end->diffInDays($now);
if now() == 2016-06-07
then
$length will be 5 days
and
$lengthFromEnd will be -1 days
.
but my code return abnormal result
Your code is correct. Only problem is you are getting unexpected results.
When you said now() == 2016-06-07
, you forgot to consider the time. Actually, now
must be something like this 2016-06-07 15:47:47
.
Since,
$start_Date='2016-06-02 18:00:13';
$end_Date='2016-06-06 18:00:13';
you will get $length = 4
and $lengthFromEnd = 0
. When the $now
becomes 2016-06-07 18:00:13
, then you'll get $length = 5
and $lengthFromEnd = 1
.
Note that you won't get $lengthFromEnd = -1
as Carbon gives difference in positive numbers.
you can also try this way.
$difference = $start_date->diff($end_date)->days;
For negative result, you need a add parameter, like this:
$absolute = false;
$end->diffInDays($now, $absoute);
This usually works perfectly but recently I had faced some problems finding the difference between to date where my date format was 12-02-2020
$endDate = Carbon::createFromFormat('d-m-Y', $data['enddate']);
$left = Carbon::parse(Carbon::now())->floatDiffInDays($endDate, false);
If the date is expired then $left
will be negative and number of days it has passed otherwise it will be a positive number