How to calculate the the interval between 2 unix timestamps in php WITHOUT dividing by 86400 (60*60*24)

流过昼夜 提交于 2019-12-06 04:23:27

问题


I have 2 unix timestamps, Im in AsiaPacific/Auckland timezone (GMT+12, DaylightSavings = GMT+13)

I want to calculate the number of days interval between 2 timestamps, where one is inside daylight savings time and one is not.

My example dates are

7 Feb 2009 (1233925200) to 21 September 2010 (1284985360) (not including 21st) see here it says 591 days: http://www.timeanddate.com/date/durationresult.html?d1=7&m1=2&y1=2009&d2=21&m2=9&y2=2010

Lets calculate, here are my timestamps (both are based on Auckland 00:00 time)

1284985360-1233925200 = 51060160
51060160 / 86400 = 590.974

So yea I need 591. I don't want to use the "round up" solution

Is there any reliable method like strtotime, but for calculating date intervals, preferably that dont need php 5.3+ minimum

EDIT: need to clarify, im using STRTOTIME to get these timestamps, I thought that was UTC

EDIT2: I believe i have found the issue. While my end date was 21 September, I was actually using time() to get my end date, and time() was returning the wrong timestamp, perhaps it doesnt account for the GMT+12, regardless I switched time() to strtotime(date('d M Y')) and it returned the correct timestamp! eureka 591 days

Cheers!


回答1:


Calculate the number of full days for both timestamps before calculating the difference:

floor(1284985360 / 86400) - floor(1233925200 / 86400)

The your result is always an integer.

And since you’re using strtotime to get these timestamps, specify the time 00:00:00+0000 to always get a multiple of 86400:

strtotime($str.' 00:00:00+0000')



回答2:


A correct Unix (POSIX) timestamp is in UTC, so you're starting out with values that are already wrong. You're facing an uphill battle, since APIs will generally assume that timestamps are in UTC. It would be best to fix this, after which the simple division would actually give the correct result.




回答3:


Dividing by 86400 is reliable and easy. I don't know any special functions and i don't see a reason for them to exist.



来源:https://stackoverflow.com/questions/3751712/how-to-calculate-the-the-interval-between-2-unix-timestamps-in-php-without-divid

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!