简体   繁体   中英

PHP datediff february issues

I'm using a code to find how many days have passed since the new year (January 1). I use this code:

$newyear = new DateTime("2017-01-01"); // January 1, 2017.
$today = new DateTime(); // March 6, 2017.
$difference = $newyear->diff($today);

Now, if I use this code, it shows the right number of days,

echo $difference->format("%a days"); // 64 days

but when I use a different format, it goes wrong.

echo $difference->format("%m months %d days"); // 2months 2 days.

I assume this is due to PHP counting February as 31 days long, so technically it is 31 + 31 + 2 days. I want it to count February as 28 or 29 days long, depending on the leap year condition. I guess there must be something in php.ini related to this. What and where to change or is there any hack?

To debug this issue with PHP incorrectly reporting difference between 2 dates we first must check a few things.

I see a few people are getting mixed results, to debug this try find out what version of the timezonedb you have

<?php
echo timezone_version_get();
?>

http://php.net/manual/en/function.timezone-version-get.php

The PECL timezonedb site can be found at https://pecl.php.net/package/timezonedb

Check to see that you have the most up to date version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM