tags:

views:

447

answers:

4

I'm not really sure what to call this. But basically I want to be able to have a user click on "Popular Stories from This Week", and it will take them to a page that will have other stuff but mainly the dates. For example, July 10-17.

I'm currently using this code:

    $seven_days_ago = date('j') - 7;
    $time_span = date('F ' . $seven_days_ago . ' - j');

Now, I ran into a problem when we entered July, because it would display something like July -3 - 4. I need a way for it to detect if the seven days ago variable is negative, and figure out what it should display. Help?

Thanks!

+1  A: 

What about using

$unix_timestamp = mktime(0, 0, 0, date("m"), date("d")-7, date("Y"));

and just take the returned unix timestamp?

Update

Just a little code snipped that will give you a full working example. However I don't like it that much :)

<?php
  $today = date("d F");  
  list($today_day, $today_month) = explode(" ", $today);
  $previous = date("d F", mktime(0, 0, 0, date("m"), date("d")-7, date("Y")));
  list($previous_day, $previous_month) = explode(" ", $previous);    
  if($today_month != $previous_month){
    echo $previous_month." ".$previous_day." - ".$today_month." ".$today_day;
  }else{
    echo $today_month." ".$previous_day." - ".$today_day;
  }  
  die();
?>
merkuro
+2  A: 

You can use strtotime for this:

$seven_days_ago = strtotime('-7 days');
$time_span = date('F j', $seven_days_ago) . ' - ' . date('F j');

The above gives me "June 28 - July 5" for $time_span.

Paolo Bergantino
Thanks a lot, everything works great!
Dixon Crews
+1  A: 

you need to use strtotime

$timeago = strtotime("7 days ago");
Gabriel Sosa
A: 

i just created a very nifty little function. Just pass it the Week number, it returns you an array of that week's days dates.

 function findWeekDates($weekNumber=null, $year=null ) {
// receives a specific Week Number (0 to 52) and returns that week's day dates in an array.
// If no week specified returns this week's dates.
    $weekNumber = ($weekNumber=='') ? date('W'): $weekNumber ;
    $year = ($year=='') ? date('Y'): $year ;

    $weekNumber=sprintf("%02d", $weekNumber);
    for ($i=1;$i<=7;$i++) {
        $arrdays[] = strtotime($year.'W'.$weekNumber.$i);
    }
    return $arrdays;
}

Example Usage - find a given week start and end dates:

$week= (isset($_GET['week']) && $_GET['week'] !=='')? $_GET['week'] : date('W') ;
$year =  (isset($_GET['year']) && $_GET['year'] !=='')? $_GET['year'] : date('Y') ;

if($week>52) {
    $week = 1;
    $year++;
}else if($week<1) {
        $week=52;
        $year--;
    }
$week_days = findWeekDates($week, $year);
$starting_date = date('Y-m-d', $week_days[0]);
$ending_date = date('Y-m-d', $week_days[6]);

hope this helps...

pixeline