第一个星期六,选定的一个月和一年

bsr*_*ddy 3 php datetime

我怎么能找到给定月份和年份的第一个星期六(由日历选择的月份和年份)?我正在使用PHP.

sha*_*mar 10

使用此功能:

<?php  
  /**
   *
   *  Gets the first weekday of that month and year
   *
   *  @param  int   The day of the week (0 = sunday, 1 = monday ... , 6 = saturday)
   *  @param  int   The month (if false use the current month)
   *  @param  int   The year (if false use the current year)
   *
   *  @return int   The timestamp of the first day of that month
   *
   **/  
  function get_first_day($day_number=1, $month=false, $year=false)
  {
    $month  = ($month === false) ? strftime("%m"): $month;
    $year   = ($year === false) ? strftime("%Y"): $year;

    $first_day = 1 + ((7+$day_number - strftime("%w", @mktime(0,0,0,$month, 1, $year)))%7);

    return @mktime(0,0,0,$month, $first_day, $year);
  }

  // this will output the first saturday of january 2007 (Sat 06-01-2007)
  echo strftime("%a %d-%m-%Y", get_first_day(6, 1, 2007)); 
?>
Run Code Online (Sandbox Code Playgroud)

致谢:php.net


[编辑]:另一个简短的方法:

像这样使用strtotime():

$month = 1;
$year = 2007;

echo date('d/M/Y',strtotime('First Saturday '.date('F o', @mktime(0,0,0, $month, 1, $year))));
Run Code Online (Sandbox Code Playgroud)

这输出:

06/Jan/2007
Run Code Online (Sandbox Code Playgroud)