4

the following code.

strtotime("first saturday", strtotime("+2 month"));

Is working correctly but with the months of April +2 month, October + 8 month, and December + 10 month is giving the second saturday in that month not the first.

Any ideas what is causing it and how to stop it.

Marvellous

Walrus
  • 19,801
  • 35
  • 121
  • 199

3 Answers3

5
$saturday = strtotime("first saturday", strtotime("+2 month", strtotime(date("01-m-Y"))));
butterbrot
  • 980
  • 6
  • 10
  • Marvellous. Simple and effective just what I wanted. – Walrus Feb 02 '11 at 15:53
  • @butterbrot If `strtotime("+2 month", strtotime(date("01-m-Y")))` is a Saturday, **you're still going to get the next**. – Linus Kleen Feb 02 '11 at 15:56
  • true, strtotime("first saturday", strtotime("+2 month", strtotime(date("01-m-Y")))-1); will that do? – butterbrot Feb 02 '11 at 16:01
  • @butterbrot No. This, too, can be a saturday. You'll need to check if `"+2 month"` is a saturday first. Like in my answer... – Linus Kleen Feb 02 '11 at 16:03
  • @linus no not sure, if `strtotime("+2 month", strtotime(date("01-m-Y")))-1` is a saturday as well, it is the wrong saturday as it is in the pref month, and we care about the next month. (?) – butterbrot Feb 02 '11 at 16:09
  • having said that, this should probably work too: `strtotime("first saturday", strtotime("+2 month last day", $now))` – butterbrot Feb 02 '11 at 16:25
1

This is because "first saturday" is calculate from the date given. If given date already is a saturday, the next one is calculated.

If you need the first saturday from a specific month, do:

$stamp = time();
$tm = localtime($stamp, TRUE);

// +1 to account for the offset, +2 for "+2 month"
$begin = mktime(0, 0, 0, $tm['tm_mon'] + 1 + 2, 1, 1900 + $tm['tm_year']);

if (6 == $begin['tm_wday']) {
//  we already got the saturday
    $first_saturday = $stamp;
} else {
    $first_saturday = strtotime('first saturday', $begin);
}
Linus Kleen
  • 33,871
  • 11
  • 91
  • 99
0

Use the first day of the month to create your origin timestamp, and then just check the month/year:

function firstSaturday($month, $year) {
    if (!is_numeric($month) && !is_numeric($year)) {
        return -1;
    }

    return strtotime('first saturday', mktime(0, 0, 0, $month, 1, $year));
}
Jared Farrish
  • 48,585
  • 17
  • 95
  • 104