1

Is there any easiest way to calculate remaining days to birthady?

there is a similar question:

Days remaining before birthday in php

but I want to use Carbon library.

like: 1989-6-30


update

    function getDifferenceTwoDate($date)
    {
        $birthday = Carbon::parse($date);

        $birthday->year(date('Y'));
        return Carbon::now()->diffInDays($birthday, false);
    }

getDifferenceTwoDate('1989-6-30')

but it returns 0

and

getDifferenceTwoDate('1991-5-22')

but it return -38

Machavity
  • 29,816
  • 26
  • 86
  • 96
S.M_Emamian
  • 16,079
  • 27
  • 115
  • 222
  • Have you tried the `diffInDays` function Carbon provides? – ceejayoz Jun 29 '17 at 19:10
  • yes, but it returns a big days: ` $startTime = Carbon::parse(date('Y-m-d')); $finishTime = Carbon::parse($date); return $finishTime->diffInDays($startTime);` – S.M_Emamian Jun 29 '17 at 19:12
  • Ah, I see. You'll have to do a bit more manual logic there, then. Take the birth date, do `->year(date('Y'))` to set the year to this year (with a bit of logic to set it to *next* year if they've already had their birthday this year), *then* do the difference in days. – ceejayoz Jun 29 '17 at 19:15
  • @ceejayoz updated question. – S.M_Emamian Jun 29 '17 at 19:37
  • As I said in my previous comment, you need logic to add a year if the birthday has already passed this year. – ceejayoz Jun 29 '17 at 19:44

1 Answers1

8

Assuming $birthday is a Carbon instance, you can reset the year to this year with:

$birthday->year(date('Y'));

Then you can get a difference in days from now. The second argument as false ensures past dates will return negative and future days will return positive.

Carbon::now()->diffInDays($birthday, false);

So if you get -30 you'd need to calculate based on next year, if you get 30, you'd have 30 days until their birthday.

Devon
  • 32,773
  • 9
  • 61
  • 91
  • @S.M_Emamian, like I said, you'd need to calculate based on the next year if it returns negative. – Devon Jun 29 '17 at 19:42