Get the First or Last Friday in a Month

后端 未结 12 2357
有刺的猬
有刺的猬 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:50

    function get_date($month, $year, $week, $day) {
        # $month, $year: current month to search in
        # $week: 0=1st, 1=2nd, 2=3rd, 3=4th, -1=last
        # $day:  0=mon, 1=tue, ..., 6=sun
    
        $startday=1; $delta=0;
        if ($week < 0) {
            $startday = date('t', mktime(0, 0, 0, $month, 1, $year)); # 28..31
            $delta=1;
        }
        $start  = mktime(0, 0, 0, $month, $startday, $year);
        $dstart = date('w', $start)-1; # last of the month falls on 0=mon,6=sun
        $offset=$day-$dstart; if ($offset<$delta){$offset+=7;}
        $newday=$startday+$offset+($week*7);
        return mktime(0, 0, 0, $month, $newday, $year);
    }
    

    This works for me, and based on the language-agnostic version :-) Only too bad, I needed to do that delta-thing (for if the last day of the month is the wanted week-day, we do not need to subtract 7)

提交回复
热议问题