Actual days between two unix timestamps in PHP

為{幸葍}努か 提交于 2019-12-04 18:11:27

Use the Julian Day

$days = unixtojd($t1) - unixtojd($t2);

or if you are not in UTC...

$days = unixtojd($t1 - $tz) - unixtojd($t2 - $tz);

where $tz is your timezone offset in seconds.

Use php5.3's DateInterval class:

$now = new DateTime();
$then = new DateTime("@123456789"); //this is your timestamp

$diff = $now->diff($then);

echo "then: " . $then->format("Y-m-d") . "\n";
echo $diff->format("%a") . " days\n";

outputs:

then: 1973-11-29
13937 days

Round the timestamps down to the nearest 86400 seconds, take the difference, and divide by 86400:

$start_time = strtotime("2012-01-15 23:59");
$end_time = strtotime("2012-01-16 00:05");

$start_time -= $start_time % 86400;
$end_time -= $end_time % 86400;

$days = ($end_time - $start_time) / 86400;

The rounding down makes each timestamp midnight of that day, and the division gives you the number of days since the epoch. This will only work in UTC, though.

<?php
$start_time = strtotime("2012-01-15 23:59");
$end_time = strtotime("2012-01-16 00:05");

$time_zone = 19800; # My time zone: UTC+0530 hours = UTC+19800 seconds

$days = intval(($end_time + $time_zone) / 86400) -
        intval(($start_time + $time_zone) / 86400);

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