Page 1 of 1

using date() need to count backwards

Posted: Thu Jan 24, 2008 8:59 pm
by Elliott
I have a directory structure like such:

/Year/Month/Day/image.jpg

Where not every day or even month necessarily exists, and day and month values have leading zeros like 01,02,03...etc.

I need to count backwards from a given date and check for the first existing date.

If I use date("d") to get the day...say 09 (which will be a string), and I want to count backwards from that...

How can I do this and end up with a day that's usable to me like 03 for instance?

Thanks,
Elliott

Re: using date() need to count backwards

Posted: Thu Jan 24, 2008 9:10 pm
by SidewinderX
You mean something like this?

Code: Select all

for($x = 0; $x <  date("d"); $x++) {
    echo date("d")-$x;
}

Re: using date() need to count backwards

Posted: Thu Jan 24, 2008 9:20 pm
by Elliott
Thanks for the reply,

I think that prints the days as (starting form the 10th say) 10,9,8,7,6...

But I need it to be 10,09,08,07...

This is what I did...correct me it there's a better way

Code: Select all

 
$day = "09";
 
while($day > 0)
    {
    if($day < 10 && (stripos($day,"0")!==0))
        {
        $day = "0".$day;
        }
    echo "<br>".$day;
    $day -= 1;
    }
 

Re: using date() need to count backwards

Posted: Thu Jan 24, 2008 9:34 pm
by califdon
I think I'd probably do it this way:

Code: Select all

function twodigit ($num) {
    if ($num < 10) {
        "0" . $num;
    } else {
        $num = trim(" " . $num);
    }
    return $num;
}

Re: using date() need to count backwards

Posted: Fri Jan 25, 2008 1:51 am
by Kieran Huggins

Code: Select all

for($i=10;$i>3;$i--){
   $i = sprintf("%02s",$i);
   // if day $i exists, do whatever
}
or maybe even

Code: Select all

for($i=10;$i>3;$i=sprintf("%02s",$i-1)){
   // if day $i exists, do whatever
}
(untested)

Re: using date() need to count backwards

Posted: Fri Jan 25, 2008 9:17 am
by Ollie Saunders
I could be wrong but won't you have to handle, for example: counting back by 5 from 02.

Consider using "for" combined with "$day = strtotime('-1 day', $day)"

Re: using date() need to count backwards

Posted: Fri Jan 25, 2008 9:47 am
by Zoxive
I would recommend a new Directory Structure.
(If its possible, or maybe future projects :lol: )

For images I usually have a timestamp with something extra on the end as the name. Then I put it in the database, for what the user called it, and what its category is and special meaning, etc etc.

Re: using date() need to count backwards

Posted: Fri Jan 25, 2008 10:40 am
by Elliott
Thanks for all the help guys. I'll give those a look.

-Elliott