11

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

例如

<?

$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
}

但在这种情况下,应该不受每天在线时间的影响。但我无法让它工作......

4

3 回答 3

38

PHP 的strtotime()功能正是您所寻找的。

例如:

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

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

strtotime('yesterday');
strtotime('-2 days ago');
strtotime('+5 days');
于 2013-06-12T14:43:04.803 回答
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";
    }
?>
于 2013-06-14T09:08:18.067 回答
3

当您使用 PHP >= 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
}
于 2013-06-13T07:19:15.787 回答