开发者

php strtotime() produce different result in window mac linux?

开发者 https://www.devze.com 2023-04-04 06:52 出处:网络
$today= date(\"Y-m-d H:i\"); $endtime = date(\"2011-09-14 00:00\"); $second= abs(time() - 开发者_如何学运维strtotime($endtime, strtotime($today, 0)));
$today   = date("Y-m-d H:i");
$endtime = date("2011-09-14 00:00");
$second  = abs(time() - 开发者_如何学运维strtotime($endtime, strtotime($today, 0)));

echo $second;

I want to find the second from future date - today date, but the result is different in all platform where:

  • mac: 21343,
  • ubuntu: 68172 and
  • window: 50175.

After convert the second to hour:minute:second, the different is around 10-15 hours. Anyone know other method that work similar to strtotime?


Maybe because the systems have different timezones or system clocks


You're making it quite complicated. date("2011-09-14 00:00") is nonsense, just "2011-09-14 00:00" will do the same thing. strtotime($today, 0) seems weird too. Only this should do just fine:

$second = abs(time() - strtotime('2011-09-14 00:00:00'));

Make sure you set the timezones to be the same on all systems using date_default_timezone_set, which is probably were your actual problem comes from.


It's probably getting the time settings from your server (which has variable time), you can set a timezone on all scripts for it to give you the same values.

date_default_timezone_set('Europe/London');; //I usually put it at the top of the script

http://php.net/manual/en/function.date.php


Your code is over complicated and has some weirdness in it, but this has already been pointed out in @deceze's answer, so I won't go over that again.

Others have also suggested possible reasons for the actual discrepancies you're seeing, so I won't go into that either.

What I will say is that I would always avoid using the strtotime() function where possible, because it is very slow and has the some potential for thowing unexpected results when the date is in an ambiguous format (ie dd-mm-yyyy vs mm/dd/yyyy). Even in cases like yours where the input is not ambiguous, it is still a very slow piece of code for what it does because it has to parse the date string without knowing what format to expect.

Recent versions of PHP provide a much better alternative if you're doing date arithmetic. Check out the date_diff() function, as well as other functions from the DateTime class. This class provides much better functionality for handling dates than the old-style PHP techniques you're using.

Note that to get the best from the DateTime class, you're going to need to be running the latest version of PHP - ie PHP 5.3. But since PHP 5.2 is no longer supported, you really ought to make sure you're on 5.3 now anyway.

Hope that helps.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号