如果文章是12个月后发布的,请停止检索文章


Stop retrieving articles if article is posted 12 months from now

我正在抓取一个页面中所有包含日期的文章,格式如下:

2012-08-20T11:04:00+0200

我想做的是停止检索文章,如果下一篇文章是从今天发布的12个月后的日期。我能想到的方法如下:

while ($retrieveArticles == true) {
    $stopDate = date('Y-m-d'); // <--- this gives me todays date while I need the date 12 months ago.
    $date = $article->find('header div p span', 1);
    $date = substr($date->title, 0, 10); // <--- becomes 2012-08-20
    if ($date >= $stopDate) {
        $retrieveArticles = false;
    }
    ... not relevant code
}

我需要帮助的地方:

  1. 我如何从今天的日期减去12个月?

  2. 我这样做是对的吗?还是有更好、更优雅的方法来实现我想要的?

提前感谢!

如果将Y-m-d格式的日期与
您需要使用strtotime()函数将其转换为时间格式。12个月就是(365*24*3600秒)。你可以这样修改函数:

while ($retrieveArticles == true) {
    $stopDate = date('Y-m-d'); // <--- this gives me todays date while I need the date 12 months ago.
    $date = $article->find('header div p span', 1);
    $date = substr($date->title, 0, 10); // <--- becomes 2012-08-20
    $stopDate = strtotime($stopDate);
    $date = (int)strtotime($date)  + (365*24*3600);
    if ($stopDate >= $date) {
        $retrieveArticles = false;
    }
}

当然可以:

$in_12_months = strtotime('+12 months');
while ($retrieveArticles == true) {
  $article_date = strtotime($article->find('header div p span', 1));
  if ($article_date >= $in_12_months) {
    $retrieveArticles = false;
  }
}

我是这样做的:

<?php
$s = strtotime('2012-02-09T11:04:00+0200');
$timeDifference = time() - $s;
echo round($timeDifference / 60 / 60 / 24 / 30);
?>

输出:11

转换2012-08-20T11:04:00+0200到时间戳:如何在PHP中转换日期到时间戳?
然后用$seconds = time()-$theresult,这是从那之后的秒数。12个月应该大致等于3100万秒

你可以这样做:

<?php
// Current date
$posted = strtotime("2012-08-20T11:04:00+0200");
// 12 months ago
$timestamp = strtotime("-12 months", $posted);
// days
$days = ($posted - $timestamp) / 60 / 60 / 24;
$get_items = true;
if($days >= 365){
    $get_items = false;
}