SitePoint Sponsor

User Tag List

Results 1 to 4 of 4
  1. #1
    SitePoint Enthusiast
    Join Date
    Oct 2009
    Location
    Byron Bay, NSW, Australia
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    DateInterval & DatePeriod alternative for PHP 5.2x

    So I programmed this in 5.3 but 5.2x doesn't support the DateInterval and DatePeriod classes.

    Can somebody assist me with making this code 5.2x friendly. I'm really not sure where to start without it turning 4 lines into 400.

    Code PHP:
    	//Create array with all dates within date span
    	$begin = new DateTime( $start_date );
    	$end = new DateTime(date("Y-m-d",strtotime("+1 day", strtotime($end_date))));
    	$interval = new DateInterval('P1D'); //P1D=Period 1 Day
    	$period = new DatePeriod($begin, $interval, $end);

    Cheers,

    Trev
    Madproject - I'm an amateur...
    What I learn from day to day

  2. #2
    SitePoint Guru bronze trophy
    Join Date
    Dec 2003
    Location
    Poland
    Posts
    925
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    Do you really need the DatePeriod object? If it's not available in PHP 5.2 then you could simply use a (for, while) loop to create the $period array and populate it with all DateTime objects at the specified interval - you can use DateTime::modify for this.

  3. #3
    SitePoint Enthusiast
    Join Date
    Oct 2009
    Location
    Byron Bay, NSW, Australia
    Posts
    54
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)
    Thanks LJ, I completely missed the modify method.

    Final working code:
    Code PHP:
    	//Create array with all dates within date span
    	$begin = new DateTime( $start_date );
    	$end = new DateTime(date("Y-m-d",strtotime("+1 day", strtotime($end_date))));
    	while($begin < $end) {
    		$period[] = $begin->format('Y-m-d');
    		$begin->modify('+1 day');
    	}
    Madproject - I'm an amateur...
    What I learn from day to day

  4. #4
    SitePoint Guru bronze trophy
    Join Date
    Dec 2003
    Location
    Poland
    Posts
    925
    Mentioned
    7 Post(s)
    Tagged
    0 Thread(s)
    Great, I didn't even know you can compare DateTime objects just like that - it looks like I learned something, too!


Bookmarks

Posting Permissions

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