TARKUS TARKUS - 6 months ago 20
MySQL Question

When adding days in PHP date, doesn't increment to next year

I'm scraping a website where I have to enter a date range to get data. My start date range is 2009-01-01 to 2009-01-14. Then I increment the next date range by 15 days, so that I'm always doing chunks of 14 days (so as not to get too much data per scrape).

The code that does this is:

$result = sqlGetState($db); //a sql query that gets the last start date - end date
$startDate = $result['startDate']; // start date from db
$endDate = $result['endDate']; // end date from db

$newStartDate = date('Y-m-d', strtotime($endDate. ' + 1 days')); // create a new start date, which is equal to the previous end date + 1 day
$newEndDate = date('Y-m-d', strtotime($newStartDate. ' + 14 days')); // create a new end date, which is equal to the new start date + 14 days.
$timestamp = date('Y-m-d H:i:s', time() ); //2016-08-07 08:42:43
$affected_rows = sqlUpdateState($db,$newStartDate,$newEndDate,$timestamp); // update the "state" table with the new date values

So what goes in my "state" table is a timestamp of when I did the operation, the new date, and the new date + 14 days.

This goes pretty well, but then at some point I check the table where I'm storing html, and I see no new pages have been stored. Then I look at my state table, and I see the

start date : 01/02/1970 and end date: 01/16/1970.

I would think PHP is "smart enough" to know that when it comes to 12/31 it should increment the date to the next year. Is this a flaw in the PHP date function, or is there something I'm supposed to be doing?


I don't think strtotime() can be used to do date arithmetic as you are doing.

I'd suggest you code it this way:

$startDate = date_create($result['startDate']);
$endDate = date_create($result['endDate']);

$newStartDate = date_add($endDate, date_interval_create_from_date_string("1 days"));
$newEndDate = date_add($newStartDate, date_interval_create_from_date_string("14 days"));
$timestamp = date_create();

See the manual: