Jason
Jason

Reputation: 2727

Third Thursday of the month in php

Is there a way to find the day of the week in php with a particular date.

I don't mean

date('D', $timestamp);

I mean if I was to supply a date like 2010-10-21 it would return "third thursday".

Upvotes: 10

Views: 2929

Answers (2)

Tatu Ulmanen
Tatu Ulmanen

Reputation: 124768

Not directly, you need a helper function for that:

function literalDate($timestamp) {
    $timestamp = is_numeric($timestamp) ? $timestamp : strtotime($timestamp);
    $weekday   = date('l', $timestamp);
    $month     = date('M', $timestamp);   
    $ord       = 0;

    while(date('M', ($timestamp = strtotime('-1 week', $timestamp))) == $month) {
        $ord++;
    }

    $lit = array('first', 'second', 'third', 'fourth', 'fifth');
    return strtolower($lit[$ord].' '.$weekday);
}

echo literalDate('2010-10-21'); // outputs "third thursday"

Working example:

http://codepad.org/PTWUocx9

Upvotes: 13

Pekka
Pekka

Reputation: 449435

strtotime() seems to understand the syntax. You just need to provide it with the first day of the month in question as a starting point.

 echo date("d.m.Y", strtotime("third thursday", mktime(0,0,0,10,1,2010))); 
 // Will output October 21

 echo date("d.m.Y", strtotime("third thursday", mktime(0,0,0,11,1,2010))); 
 // Will output November 18

Upvotes: 4

Related Questions