Reputation: 107
I am having a hard time getting a simple date check to work properly. I searched all the questions, and so far none of the solutions have helped me.
I want to do a loop from a certain date, until today.
What is currently happening with the below code is that its not stopping and just keeps going. When I log i, I can see the date is increasing by a day like it should. I also tried flipping the operator to <, but that caused the loop to be skipped entirely.
Any ideas?
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = $startOfPlayoffs; $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}
Interestingly, when I hard-code the date, it works fine. I.E:
$endOfPlayoffs = new DateTime( "2016-05-02" );
That isn't ideal, so was hoping to get it to work properly.
Upvotes: 0
Views: 918
Reputation: 2129
use: date_format($startOfPlayoffs,"Y-m-d")
to obtain a "variable" you can compare against...
$startOfPlayoffs = new DateTime( "2016-04-29" );
$today = date("Y-m-d");
for($i = date_format($startOfPlayoffs,"Y-m-d"); $i >= $today; $i->modify('+1 day'))
{
//... some stuff
}
Upvotes: 0
Reputation: 94642
Use the ->diff()
method of the DateTime class like this is quite clean
The ->diff()
method produces an DateInterval Object that looks like this
DateInterval Object
(
[y] => 0
[m] => 3
[d] => 4
[h] => 17
[i] => 23
[s] => 4
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 95
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
So the code can be as simple as this
<?php
$startOfPlayoffs = new DateTime( "2016-01-29" );
$today= new DateTime();
$diff = $startOfPlayoffs ->diff($today);
for ( $i = 0; $i<$diff->days; $i++ ) {
// do stuff
}
Upvotes: 0
Reputation: 836
You are comparing a PHP Date object ($startOfPlayoffs) with a string ($today). Try converting $today into a Date object:
$startOfPlayoffs = new DateTime("2016-04-29");
$today = new DateTime();
$cpt = 0;
for($i = $startOfPlayoffs; $i <= $today; $i->modify('+1 day')){
echo time($i) . "<br>";
if ($cpt++ >= 100) exit;// as a safeguard
}
Upvotes: 2
Reputation: 972
use unix time stamps, they are concrete numbers that are much easier to deal with.
int time(void) //current time stamp
You can also use strtotime()
to convert date strings into time stamps. See this question for conversion from numbered date formats to unix timestamps.
Upvotes: 1