First saturday for a selected month and year
How could I find the first Saturday for开发者_开发技巧 a given month and year (month & year selected by a calender)? I am using PHP.
Use this function:
<?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));
?>
Credits: php.net
[EDIT]: Another short way:
Use strtotime() like this:
$month = 1;
$year = 2007;
echo date('d/M/Y',strtotime('First Saturday '.date('F o', @mktime(0,0,0, $month, 1, $year))));
This outputs:
06/Jan/2007
Here is one-liner:
$firstSat = strtotime( 'first Saturday', strtotime( "$month $year" ) );
Test:
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>" ;
}
Outputs:
Jan, 2017 1483747200 2017-Jan-07
Feb, 2017 1486166400 2017-Feb-04
Nov, 2017 1509753600 2017-Nov-04
Dec, 2017 1512172800 2017-Dec-02
精彩评论