tags:

views:

54

answers:

1

How could I find the first Saturday for a given month and year (month & year selected by a calender)? I am using PHP.

+4  A: 

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
shamittomar
hi shamit bro.. first of all thx for ur reply. but in both cases its showing a warning like <b>Warning</b>: mktime() expects parameter 4 to be long, string given ... i am entirely new to php so could u help me to sort out this.. thx.
bsrreddy
@bsrreddy, I have updated both codes to suppress warnings. Try now.
shamittomar
hmm...code is working fine bro. but the result is not correct itseems. i selected 02-jan-2010 in my calender where this date is a first saturday of that month. but the result it showing is 03/Jan/2009 where it should be 02/jan/2009.
bsrreddy
hope some thing is going wrong with the year.
bsrreddy
The functions are correct. Try to run them in a empty separate PHP code file. There must be some other problem in your code and calendar.
shamittomar
i am also thinking that there would be problem with calender.. let me check out and call you back brother. thank you.
bsrreddy
hi.. i am sorry bro.. as i am very new i could not find the problem,,which causing all this fishy..shall i post all my content so that u can understand what exactly i want?
bsrreddy
hi shamit gi..i need some calriffication.what is 'F o' doing below..plz explain me. echo date('d/M/Y',strtotime('First Saturday '.date('F o', @mktime(0,0,0, $month, 1, $year))));
bsrreddy
@bsreddy, `F o` are the *formatting options* for php function [`date`](http://php.net/date). The `F` is the full textual representation of month and `o` is the ordinal number of the year, thus effectively representiang the full string as "First Saturday January 2007".
shamittomar
oh..thx brother..finally thx alot for helping me. i checked through my calender and now ur function is working like a champ. thx. see u .
bsrreddy
You're welcome.
shamittomar