Page 1 of 1

Printing Out Last Year's Dates

Posted: Mon Mar 13, 2006 6:06 pm
by icesolid
The code below prints out all of the dates one year from today in a selection box. It works great, however now on another spot on my site I want to print out all of the dates one year past from today, kind of reverse the code below.

Code: Select all

<select name="end_date">
<option value="">------ Select A Date ------</option>
<?php
$start = time();
$time = $start;
$end = strtotime("1 year", $start);

do {
    echo "<option value=\"" . date("Y-m-d", $time) . "\">" . date("m-d-Y", $time) . "</option>\n";
    $time = strtotime("1 day", $time);
}

while($time < $end); 
?>                    
</select>

Posted: Mon Mar 13, 2006 6:22 pm
by RobertGonzalez
Have you tried something like this. I haven't, just thought I'd throw it out there...

Code: Select all

<select name="end_date">
<option value="">------ Select A Date ------</option>
<?php
$start = strtotime("-1 year", time());
$time = $start;
$end = time();

do {
    echo "<option value=\"" . date("Y-m-d", $time) . "\">" . date("m-d-Y", $time) . "</option>\n";
    $time = strtotime("1 day", $time);
}

while($time < $end); 
?>                    
</select>

Posted: Mon Mar 13, 2006 6:31 pm
by icesolid
Yes I have, strtotime(); does not seem to work as easy as it would appear.

Posted: Mon Mar 13, 2006 6:36 pm
by RobertGonzalez

Code: Select all

<select name="end_date">
<option value="">------ Select A Date ------</option>
<?php
$start = time() - 31536000; //Today less one year
$time = $start;
$end = time();

do {
    echo "<option value=\"" . date("Y-m-d", $time) . "\">" . date("m-d-Y", $time) . "</option>\n";
    $time = strtotime("1 day", $time);
}

while($time < $end); 
?>                    
</select>
OK, how about if you just subtract a year's worth of seconds and start a year ago?

Posted: Mon Mar 13, 2006 6:42 pm
by icesolid
Works great, one question left. How would I make that today date dynamic, like tomorrow it will be a different date and I want this to change by it's self.

Posted: Mon Mar 13, 2006 6:48 pm
by nickman013
Thats a sick script. I just tried it out. Very cool!

I didnt know that was possible.

Posted: Mon Mar 13, 2006 6:54 pm
by icesolid
Yeah, it is very useful when searching a database by start and end dates.

How would I make the start dynamic to one year past todays date?

Posted: Mon Mar 13, 2006 6:55 pm
by RobertGonzalez
You could use a for loop...

Code: Select all

<select name="end_date">
<option value="">------ Select A Date ------</option>
<?php 
$end = time(); 
$start = $end - 31536000; //Today less one year

for ($i = $start; $i < $end; $i += 86400)
{
    echo "<option value=\"" . date("Y-m-d", $i) . "\">" . date("m-d-Y", $i) . "</option>\n";
}
?>                    
</select>