开发者

PHP error when using strtotime

Hi I get an error when trying to get date interval using php strtotime function th开发者_如何学运维e code is:

 <?php
    $interval = time() - strtotime('1992/08/13');

    //expect to be 18
    // but the output is 1988
    print date('Y', $interval);
 ?>

any advice?

thanks


If you want to deal with date intervals in PHP I can't recommend the DateInterval class enough. I wrote a blog post on this earlier this week: Working with Date and Time in PHP

There's an example of using it there that should allow you to do what you want to do.


That is because all time() functions are seconds since epoch which is in 1970, so your out is actually 18 years since epoch. If you want it to get the difference in years you will probably have to calculate the difference yourself.

print $interval / (60*60*24*365.242199);


Are you tring to get the years elapsed rather than the actual year?

If so:

$year = 31556926;

$interval = time() - strtotime('1992/08/13');
print round($interval / $year);


$interval = time() - strtotime('1992/08/13');

These PHP functions deal with UNIX timestamps. That means the number of seconds from 1970. 01. 01. So 1992/08/13 is transformed into a timestamp (seconds). time() gives the current timestamp (seconds). You subtract the former from the latter, and you get the amount of seconds between those two dates. This is not a date itself, just an interval.

If you want to get the year, do something like echo $interval/(60*60*24*365); which will convert your seconds to years (not accurate, leap years will not be taken into consideration). Though your best option is checking out @James C's link and use his solutions. I just wanted to give some explanation.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜