2

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
  • 30,841
  • 27
  • 92
  • 100
S.M_Emamian
  • 17,005
  • 37
  • 135
  • 254
  • 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

9

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 Bessemer
  • 34,461
  • 9
  • 69
  • 95