问题
I need to calculate the number of decades between 2 dates possible spanning form 1708 until today - the limitations are as far as I can gather are 1970/1901 within PHP native functions.
Can anyone advise?
Thanks!
回答1:
If you have PHP >= 5.3.0:
$before = new DateTime('1708-02-02');
$decades = $before->diff(new DateTime())->y / 10;
回答2:
You could use Zend_Date. It's part of the Zend Framework but can be used standalone, you don't need to install the whole framework to use it. It can work with dates beyond 1901 if the bcmath
extension is installed into your PHP. From Zend_date's theory of operation:
This was only possible, because Zend_Date is not limited to UNIX timestamps nor integer values. The BCMath extension is required to support extremely large dates outside of the range Fri, 13 Dec 1901 20:45:54 GMT to Tue, 19 Jan 2038 03:14:07 GMT. Additional, tiny math errors may arise due to the inherent limitations of float data types and rounding, unless using the BCMath extension.
I like to recommend Zend components because they are well-groomed, high-quality code. There are other solutions to this, though, for example using the mySQL date functions.
回答3:
I would write a custom method.
PHP date functions are based on the epoch ( 1969 ) so there won't be much help there.
If your just looking at years that is simple math
higher year - earlier year = years years / 10 = decades.
If you mean decades from an even 01-10, 11-20 then you could do some rounding. (round early date up, later date down to nearest 10.
来源:https://stackoverflow.com/questions/2184506/calculate-date-difference-having-a-large-range-with-php