views:

150

answers:

3

I need to write some code in PHP that performs an action only on alternating weeks, based on the day of the week (mon, tue etc) rather than the number (1st, 7th etc).

So on a cycle starting on a Monday it should run for one week then not the following week.

I am sure this must be easier than I think but can't seem to work it out, so help please!

+7  A: 

You could simply take the week number, and perform your action when it is odd (or even!), if the day is monday, for example:

$time=time();
$dayNo=strftime('%u', $time);  #1=monday
$weekNo=strftime('%U', $time); #week number

if (($dayNo==1) && ($weekNo%2))
{
   #do something on mondays, alternating weeks
}
Paul Dixon
scragar
+1 - You'll need to work out whether the week number of the first occurrence is even or odd first, and adjust accordingly, but that should be very straightforward (try adding the numbers of the first occurrence's week with the current week number together before doing `%2`).
Dominic Rodger
You wait until the modulus operation becomes a bottleneck before worrying about that! Using modulus communicates the intent better, and also makes it easy to run every 3rd, 4th, 5th week or whatever...
Paul Dixon
question is, how many modulo operations would it take to bring down the server? lol
bucabay
@scragar: PHP is an interpreted language, meaning there are bottlenecks in the system that render any tiny optimizations you make moot. PHP is not built for sub-millisecond speed, it's built for ease of development and maintenence. http://www.google.com/search?q=premature+optimization
dcousineau
A: 

Something to keep in mind is that the strtotime() function is very robust and can give you fuzzy information like the second Sunday in March ("Second Sunday March 0").

For example, to find the Sunday that marks the second week of this month:

<?php
$month = time();

// Calculate the first day of the month contained in the $month timestamp
$first_day = strtotime(
    date(
        'Y-m-1 00:00:00',
        $month
    )
);

// Calculate the sunday opening the week that contains the first day
// of the month (e.g. August 30th, 2009 is the Sunday that corresponds 
// to September 1st, 2009)
$pseudo_first_sunday = strtotime(
    'First Sunday',
    strtotime(
        '-1 Week',
        $first_day
    )
);

var_dump(date( 'Y-m-d', strtotime('Second Week', $pseudo_first_sunday) ));

The output of this script will be (as of 2009-9-14):

string(10) "2009-09-06"

Which is the second week of September (however not the second FULL week, if you want that substitute $first_day in for $pseudo_first_sunday).

Just something to keep in mind when playing with dates in PHP.

dcousineau
+1  A: 

Whilst Paul Dixon nailed it, if you're after a one liner, you could simply do...

if(date('W') % 2) {
// Will only execute on alternate weeks.

}
middaparka