0

I'm scraping a page for articles which all contains of a date in the following format:

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

What I want to do is to stop retrieve articles if the next article is posted 12 months from todays date. The way I can think of is the following:

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

}

What I need help with:

  1. How can I subtract 12 months from todays date?

  2. Am I thinking right by doing like this or is there better and more elegant ways of achieve what I want?

Thanks in advance!

holyredbeard
  • 19,619
  • 32
  • 105
  • 171

5 Answers5

1

Yes, for sure :

$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;
  }
}
Epoc
  • 7,208
  • 8
  • 62
  • 66
1

Here's how I did it:

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

Output: 11

David Harris
  • 2,697
  • 15
  • 27
1

it will be wrong if you compare Y-m-d format of date with together :
you need to convert that to time format with strtotime() function . for 12 month that is ( 365*24*3600 sec) . so you can change your function like this :

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;
    }
}
M Rostami
  • 4,035
  • 1
  • 35
  • 39
0

Convert 2012-08-20T11:04:00+0200 to a timestamp: How to convert date to timestamp in PHP?
and then just do $seconds = time()-$theresult this will be the number of seconds since then. 12 months should be roughly equals to 31 Million Seconds

Community
  • 1
  • 1
Stefan
  • 2,164
  • 1
  • 23
  • 40
0

You could do something like this:

<?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;
}
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338