Dinuka Thilanga
Dinuka Thilanga

Reputation: 4330

Get date in Leap years php

I want to convert 59 to 2012-feb-29. I already know current year is 2012. I try following code. but it give 2012-mar-01.

$string = '59 2012';
$date1 = date_create_from_format('z Y', $string);
$date_time = date_format($date1, 'Y-m-d');
echo $date_time;

Upvotes: 1

Views: 278

Answers (3)

Maya
Maya

Reputation: 13

I've encountered this issue before and this is the solution I came up to:

/**
 * Get date if leap year
 * 
 * @param int $year z date format
 * @param int $date Y date format
 * 
 * @return object|null
 */
private function getLeapYearDate($year, $date)
{
    if ($date >= 1 && $date <= 59) {
        return date_create_from_format('z', $date - 1);
    } else if ($date == 60) {
        return date_create($year . '-02-29');
    } else if ($date >= 61 && $date <= 365) {
        return date_create_from_format('z', $date - 2);
    } else if ($date == 366) {
        return date_create($year . '-12-31');
    }

    return null;
}

Hope this helps! Have a good day...

Upvotes: 0

xdazz
xdazz

Reputation: 160883

Try:

echo date('Y-m-d', strtotime(date('Y-01-01')) + 59 * 86400);

Update:

The problem in your code is because z is starting from 0, so you need to minus 1.

$date1 = date_create_from_format('z', 59 - 1);
$date_time = date_format($date1, 'Y-m-d');
echo $date_time;

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173642

You could use strtotime() instead:

echo date('Y-m-d', strtotime('2012-01 +59 day'));

Upvotes: 1

Related Questions