Get the First or Last Friday in a Month

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

    Perhaps it can be made quicker...
    This was VERY interesting to code.

    Please note that $direction is 1 for forward and -1 for backward to ease things up :)
    Also, $day begins with a value of 1 for Monday and ends at 7 for Sunday.

    function get_date($month, $year, $week, $day, $direction) {
      if($direction > 0)
        $startday = 1;
      else
        $startday = date('t', mktime(0, 0, 0, $month, 1, $year));
    
      $start = mktime(0, 0, 0, $month, $startday, $year);
      $weekday = date('N', $start);
    
      if($direction * $day >= $direction * $weekday)
        $offset = -$direction * 7;
      else
        $offset = 0;
    
      $offset += $direction * ($week * 7) + ($day - $weekday);
      return mktime(0, 0, 0, $month, $startday + $offset, $year);
    }
    

    I've tested it with a few examples and seems to work always, be sure to double-check it though ;)

提交回复
热议问题