php - Difference Date Calculation -
i've problem calculating difference between 2 dates (including end date) using carbon. here's problem:
i'm using code (source: danharper's answer in https://laracasts.com/discuss/channels/general-discussion/carbon-display-age-in-years-months-day?page=1) :
$datefrom = new carbon("2017-01-01"); $dateto = new carbon("2017-12-31"); $dateto = $dateto->addday(); //including end date echo $datefrom->diff($dateto)->format('%y') . " year, <br>"; echo $datefrom->diff($dateto)->format('%m') . " month, <br>"; echo $datefrom->diff($dateto)->format('%d') . " day <br>"; echo "difference " . $datefrom->diffindays($dateto) . " days <br>";
scenario 1:
let's say, $date1 = 2017-01-01
, $date2 = 2017-12-31
, it'll results:
1 year, 0 month, 0 day difference 365 days
when i'm using date calculator in https://www.timeanddate.com/date/durationresult.html?d1=1&m1=1&y1=2017&d2=31&m2=12&y2=2017&ti=on, it'll results:
it 365 days start date end date, end date included or 1 year including end date
they resulting same answer. but:
scenario 2:
$date1 = 2017-10-01
, $date2 = 2017-12-31
, it'll results:
0 year, 3 month, 1 day difference 92 days
using date calculator in https://www.timeanddate.com/date/durationresult.html?d1=1&m1=10&y1=2017&d2=31&m2=12&y2=2017&ti=on, it'll results:
it 92 days start date end date, end date included or 3 months including end date
the result in timeanddate.com 3 months only. not 1 day.
i want result 3 months (the timeanddate.com's answer).
how can achieve answer?
or, if can't achieved, there other technique achieve: x months y days
?
(ex: 1 jan 2017
~ 5 feb 2019
= 25 months, 5 days
)
please me.
you can change code following,
$datefrom = new carbon("2017-01-01"); $dateto = new carbon("2017-12-31"); $dateto = $dateto->addday(); //including end date $days = $datefrom->diffindays($dateto); $months = $datefrom->diffinmonths($dateto); $years = $datefrom->diffinyears($dateto);
in code, have measured difference many times instead of 1 time. use diffindays()
, diffinmonths()
, diffinyears()
functions values of days, months , years between 2 dates.
hope understand.
Comments
Post a Comment