Alex
Alex

Reputation: 9

Want to add dates for week

I am using this code to add a week to a date:

$date1 = "2009-10-11";
$d = new DateTime($date1);
$d->modify( '+1 week' ); 
echo $d->format( 'Y m d' ), "\n";

It works fine good but want to add this functionality:

$startDate = "2009-10-11";
$endDate = "2010-01-20";

And want to create an array that holds ALL the +1 weeks IN BETWEEN these dates. How can i do this?

Upvotes: 0

Views: 46

Answers (2)

msound
msound

Reputation: 445

Here is one way of doing it:

$startDate = "2009-10-11";
$endDate = "2010-01-20";

$dates = array();
$temp = strtotime($startDate);

do {
  $dates[] = date("Y-m-d", $temp);
  $temp = strtotime("+1 week", $temp);
} while ($temp < strtotime($endDate));

print_r($dates);

You can see a demo here

Upvotes: 2

nstCactus
nstCactus

Reputation: 5183

Dates can be converted to timestamps. Timestamps are great for being compared because they basically just integers.

What I would do as a quick'n'dirty solution is to convert both your dates to timestamps and then design a loop like this (pseudo-code) :

timestamp = start_timestamp
WHILE timestamp < end_timestamp
    timestamp = timestamp + 1 week
    dates[] = timestamp
END WHILE

Upvotes: 0

Related Questions