PHP在一周后获取日期并计算剩余天数

时间:2014-05-25 08:12:46

标签: php date comparison

我有一个动态约会,现在我想要的是在确切的一周之后找到日期,我已经用下面的代码实现了这个,但是现在我想要的是现在很多天都会留在那个星期后的日期。我有一些时间戳,但我不知道如何将它转换为DAYS LEFT。

$weekDate = date( "d/m/Y", strtotime("19-05-2014") + 86400 * 7 );

echo $weekDate;// THATS PERFECT

////////////////////////////////////////////////////////////////

$future = strtotime( $weekDate ); //Future date.

$datediff = time() - $future;

$days = floor( ( ( $datediff / 24 ) / 60 ) / 60  ); //this is not perfect, returns some 

某种时间戳

我已经尝试了其他很好的方法,但是如果一周完成26,今天是25,它给我0天,但它应该说还剩1天。请帮帮我。

3 个答案:

答案 0 :(得分:2)

在你的$date_diff现在小于未来的日期,为什么它为零。在strtotime()函数内,您可以直接在其中放置相对日期。在这种情况下,您可以使用+1 week+7 days一周。考虑这个例子:

$next_week = date('d/m/Y', strtotime('19-05-2014 +1 week')); // 26/05/2014
$next_week = strtotime('19-05-2014 +7 days');
$difference = $next_week - time(); // next weeks date minus todays date
$difference = date('j', $difference);
echo $difference . (($difference > 1) ? ' days ' : ' day ') . ' left';
// should output: 1 day left

答案 1 :(得分:1)

好的。我做了一些事。这是代码

$startDate = strtotime("19-05-2014");

$endDate = $startDate + 604800;

$diff = ($endDate - time()) / 60 / 60 / 24;

if ($diff < 1 && $diff > 0) {
    $days = 1;
} else {
    $days = floor($diff);
}

echo $days;

你得到的问题&#34; 1天&#34;如果明天的日期是落地法。 strtotime()给你的时间是凌晨0点,如果你不是自己设置的话。因此,现在和明天之间的差异小于1,如果你这样做,则为0。我为此创建了一个if子句。 但这会给你#1; 1天&#34;今天和&#34; 1天&#34;昨天(最后一天的最后2天)。如果你想要更好,你必须在初始日期(19-05-2014)指定时间。

答案 2 :(得分:0)

使用DateTime进行日期和时间计算。

$weekDate = new \DateTime('+ 1 week');
$future = new \DateTime('+ 3 days');
$daysLeft = $weekDate->diff($future)->days;
echo $daysLeft; //4

See it working

参考http://php.net/datetime