php一周前得到日期

时间:2013-06-12 14:40:53

标签: php date

我正在尝试为一周内的元素创建一个选择器。我得到一个像Sun, 02 Jun 2013 22:05:00 GMT这样的时间戳,但选择器不应受时间的影响

E.G。

<?

$curdate = date( 'D, d M Y H:I:s' );
$olddate = "Sun, 02 Jun 2013 22:05:00 GMT";

if($curdate < $olddate){
    // Date is with in a week
} else {
    // Date is older then a week
}

但在这种情况下,它不应该受到当天在线时间的影响。但我无法让它发挥作用......

3 个答案:

答案 0 :(得分:31)

PHP的strtotime()功能正是您所需要的。

例如:

echo date('jS F Y H:i.s', strtotime('-1 week'));

您可以将许多不同的字符串输入strtotime()函数,例如:

strtotime('yesterday');
strtotime('-2 days ago');
strtotime('+5 days');

答案 1 :(得分:4)

您应该只在比较日期之外创建日期。之后,您应该创建给定日期Sun, 02 Jun 2013 22:05:00 GMT的时间戳,并且应该将其转换为仅包含日期的日期字符串。然后你创建另一个时间戳......

如果你知道我的意思......这应该有效:

<?php
    // First create the date

    $date = 'Sun, 02 Jun 2013 22:05:00 GMT';

    // To a timestamp
    $t_date = strtotime($date);

    // Noew remove the seconds: First create a new date, with a timestamp of the give date.
    // After that create a datestring with only the date
    $date = date("jS F Y", $t_date);
    // And create a new timestamp
    $t_date = strtotime($date);

    // One week back: time - 60 seconds * 60 minutes * 24 hours * 7 days * -1 to get backwards
    // And we only create a date of this
    $weekback = date('jS F Y', time() + (60 * 60 * 24 * -7) );
    // Create a timestamp
    $t_weekback = strtotime($weekback);

    // Debug
    echo "Date: $date<br/>Date (UTC): $t_date<br/>";
    echo "Last week: $weekback<br/>Last week (UTC): $t_weekback<br/>";

    if ($t_date <= $t_weekback) {
        //Date is older then a week
        echo "Outside a week: last week($t_date) <= The date($t_weekback)";
    }else{
         //Date is within a week
         echo "Within a week: $t_date > $t_weekback";
    }
?>

答案 2 :(得分:2)

当您使用PHP&gt; = 5.3时,您可以使用以下内容:

<?php

$date     = new DateTime('Sun, 02 Jun 2013 22:05:00 GMT');
$interval = new DateInterval('P1W');

if(new DateTime() < $date->add($interval)){
    //date is with in a week
}{
    //date is older then a week
}