简体   繁体   中英

Existing script to loop through date range by day, week, month, year?

I'm trying to find an existing helper function that will accept a start and end date and interval (day, week, month, year), and will return an array each day, week month or year in that range.

Would love to find a pre-existing one if it's out there.

Thanks!

Here's a rough start:

function makeDayArray( $startDate , $endDate ){
 // Just to be sure - feel free to drop these is your sure of the input
  $startDate = strtotime( $startDate );
  $endDate   = strtotime( $endDate );

 // New Variables
  $currDate  = $startDate;
  $dayArray  = array();

 // Loop until we have the Array
  do{
    $dayArray[] = date( 'Y-m-d' , $currDate );
    $currDate = strtotime( '+1 day' , $currDate );
  } while( $currDate<=$endDate );

 // Return the Array
  return $dayArray;
}

In PHP 5.3 and later you can use DateInterval class for that

http://www.php.net/manual/en/class.dateinterval.php

I found this thread while I was looking for this same thing. Here is what I came up with that worked great.

I had a database of email addresses and unix timestamps of when they subscribed to an email list. I wanted to see what the weekly subscribe rate was.

$startdate = 1325376000; // Jan 1 2012
//$startdate = 1293926400; // Jan 1 2011
$currentstart = $startdate;
$currentend = $startdate + 604800; // 604800 = 1 week

while($currentend < 1356998400) {
    $sql = "SELECT * FROM the_table WHERE unixdate > $currentstart AND unixdate <= " . ($currentstart + 604800 - 1);
    $result = mysql_query($sql);
    echo date('D Y-m-d', ($currentstart)) . " - " .  date('D Y-m-d', ($currentstart + 604800 - 1)) . ": <strong>" . mysql_num_rows($result) . "</strong><br />";
    $currentstart = $currentend;
    $currentend += 604800;
}

You could change the 604800 number to do intervals of 30 days or 365 days or daily or whatever.

I'm sure this isn't pretty -- I'm not the best coder -- but I had to leave my solution for those that come behind me.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM