Get the First or Last Friday in a Month

后端 未结 12 2373
有刺的猬
有刺的猬 2020-11-29 12:12

I\'m trying to write a calendar function like this

function get_date($month, $year, $week, $day, $direction)
{
    ....
}

$week

12条回答
  •  余生分开走
    2020-11-29 12:56

    Below is the quickest solution and you can use in all conditions. Also you could get an array of all day of week if you tweak it a bit.

    function findDate($date, $week, $weekday){
        # $date is the date we are using to get the month and year which should be a datetime object
        # $week can be: 0 for first, 1 for second, 2 for third, 3 for fourth and -1 for last
        # $weekday can be: 1 for Monday, 2 for Tuesday, 3 for Wednesday, 4 for Thursday, 5 for Friday, 6 for Saturday and 7 for Sunday 
    
        $start = clone $date;
        $finish = clone $date;
    
        $start->modify('first day of this month');
        $finish->modify('last day of this month');
        $finish->modify('+1 day');
    
        $interval = DateInterval::createFromDateString('1 day');
        $period = new DatePeriod($start, $interval, $finish);
    
        foreach($period AS $date){
            $result[$date->format('N')][] = $date;
        }
    
        if($week == -1)
            return end($result[$weekday]);
        else
            return $result[$weekday][$week];
    }
    
    
    $date = DateTime::createFromFormat('d/m/Y', '25/12/2016');
    
    # find the third Wednesday in December 2016
    $result = findDate($date, 2, 3); 
    echo $result->format('d/m/Y');
    

    I hope this helps.

    Let me know if you need any further info. ;)

提交回复
热议问题