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

时间:2010-09-10 06:29:05

标签: php datetime

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

2 个答案:

答案 0 :(得分: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)); 
?>

致谢: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))));

输出:

06/Jan/2007

答案 1 :(得分:0)

这是单行:

$firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );

测试:

foreach( array("Jan","Feb","Nov","Dec" ) as $month)
{
   $year = '2017';
   echo "$month, $year";
   $firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );
   $date = date( 'Y-M-d', $firstSat );
   echo " $firstSat $date <br>" ;
}

输出:

Jan, 2017 1483747200 2017-Jan-07
Feb, 2017 1486166400 2017-Feb-04
Nov, 2017 1509753600 2017-Nov-04
Dec, 2017 1512172800 2017-Dec-02