Efficient PHP date comparison
I'm trying to write a function that will return the number of days between two dates as quickly as possible. This function gets called thousands ofa million times in my code and optimizing it to the max would be really helpful. The dates are strings in the format yyyy-mm-dd
.
Here's the best I have so far:
protected function daysBetween($date1, $date2)
{
list($year1,$month1,$day1) = explode('-',$date1);
开发者_高级运维 list($year2,$month2,$day2) = explode('-',$date2);
return (int)abs((mktime(0,0,0,$month1,$day1,$year1) -
mktime(0,0,0,$month2,$day2,$year2)) / 86400);
}
How can I make this execute in the shortest amount of time possible?
Changing mktime()
to gmmktime()
reduces the time taken by over 50% for me. That's the single greatest improvement* that I can see.
* I didn't look very hard. SO doesn't seem the right place for tweaking your function, for your script, for your hardware, for your individual needs, especially since it's only called thousands of times.
精彩评论