简体   繁体   English

高效的PHP日期比较

[英]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 of a 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 . 日期是格式为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 . 更改mktime()gmmktime()减少了50%以上为我所用的时间。 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. 因此,似乎不适合调整功能,脚本,硬件,个人需求,特别是因为它仅被调用过数千次。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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