Walrus
Walrus

Reputation: 20484

PHP strtotime giving the wrong date for certain months

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

Upvotes: 4

Views: 1021

Answers (3)

Linus Kleen
Linus Kleen

Reputation: 34662

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);
}

Upvotes: 1

Jared Farrish
Jared Farrish

Reputation: 49238

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));
}

Upvotes: 0

butterbrot
butterbrot

Reputation: 970

$saturday = strtotime("first saturday", strtotime("+2 month", strtotime(date("01-m-Y"))));

Upvotes: 5

Related Questions