Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 4 of 4
  1. #1
    Regular Coder byuhobbes85's Avatar
    Join Date
    Oct 2006
    Location
    Ames, Iowa, USA
    Posts
    116
    Thanks
    9
    Thanked 4 Times in 4 Posts

    Iterate through DateTime range

    Simple question...

    I would like to iterate through a range of dates--I'm thinking PHP's DateTime class will work best for this. Here is the question--if I have a start date and an end date, how can I iterate through every date between the two (inclusive)?

    Did I state this clearly?

    Thanks!
    -- </byuhobbes>

  • #2
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    What version of PHP are you using?
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • #3
    Regular Coder byuhobbes85's Avatar
    Join Date
    Oct 2006
    Location
    Ames, Iowa, USA
    Posts
    116
    Thanks
    9
    Thanked 4 Times in 4 Posts
    5.2.11
    -- </byuhobbes>

  • #4
    God Emperor Fou-Lu's Avatar
    Join Date
    Sep 2002
    Location
    Saskatoon, Saskatchewan
    Posts
    16,987
    Thanks
    4
    Thanked 2,660 Times in 2,629 Posts
    Dang. 5.3.0 has a DatePeriod class thats built in to do just this task for you.
    Prior to this, I'd probably just do a loop to step through it since pretty much all date mathematics are unavailable.
    Something like this will probably do it:
    PHP Code:
    $now strtotime('now');
    $later strtotime('next week'$now);
    $format 'F j, Y';
    $step '+1 day';

    while (
    $now $later// maybe <=?
    {
        
    printf("Date: %s<br />"date($format$now));
        
    $now strtotime($step$now);

    Now, to do the same when DatePeriod is available, methinks its like so:
    PHP Code:
    $now = new DateTime();
    $later = new DateTime('next week');
    $period = new DatePeriod($now'P1D'$later);
    foreach (
    $period AS $day)
    {
        print 
    $day->format('F j, Y');

    DateTime would be useful, except that without any of the subtraction or difference methods it becomes a little on the useless side.
    PHP Code:
    header('HTTP/1.1 420 Enhance Your Calm'); 

  • Users who have thanked Fou-Lu for this post:

    byuhobbes85 (06-30-2010)


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •