jodonnell
jodonnell

Reputation: 50487

How can you get the number of days since year 0 in PHP?

It's the equivalent of the MySQL to_days() function.

Is there a builtin PHP function that does this, or do I need to cobble something together?

Upvotes: 1

Views: 5074

Answers (2)

John Conde
John Conde

Reputation: 219874

You'd need to write your own but it's not hard:

$now = new DateTime();
$zero = new DateTime('0000-00-00'); // -0001-11-30 - Nov 30, 1 BC. Interesting.
$diff = $now->diff($zero);
echo $diff->format('%a days'); // 735728 days

Demo using the literal year zero. You obviously would want to put a valid date in there instead.

$now = new DateTime();
$zero = new DateTime('0001-01-01'); 
$diff = $now->diff($zero);
echo $diff->format('%a days'); // 735330 days

Demo

As a one liner:

echo (new DateTime())->diff(new DateTime('0001-01-01'))->format('%a days');

As a function:

function toDays($date) {
    return (new DateTime())->diff(new DateTime($date))->format('%a');
}

Upvotes: 8

VMai
VMai

Reputation: 10336

You can use the Julian day count, i.e. with cal_to_js(), see http://www.php.net/manual/de/function.cal-to-jd.php, even if there was no year 0 in the Gregorian calendar.

Upvotes: 1

Related Questions