Advertisement
Guest User

Untitled

a guest
Oct 4th, 2015
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.47 KB | None | 0 0
  1. <?php
  2.  
  3. echo (getWeekOfMonth( time() ) . "<BR>"); //today
  4. echo (getWeekOfMonth('2015-10-13') . "<BR>");
  5.  
  6. /**
  7.  * @param $time Either in timestamp or a date format that will be accepted by strtotime()
  8.  * @return day of month (1-based), or bool FALSE on failure
  9.  */
  10. function getWeekOfMonth($time)
  11. {
  12.     // If we have something that is not in timestamp format,
  13.     // convert it, if we can
  14.     if (($tmp = strtotime($time)) !== false) {
  15.         $time = $tmp;
  16.     }
  17.  
  18.     // Get the day of the month, in numerical format
  19.     $dayOfMonth = date('j', $time);
  20.  
  21.     // Get the timestamp for the first day of the month
  22.     $firstDayOfMonthTime = $time - ($dayOfMonth - 1) * 60 * 60 * 24;
  23.  
  24.     // Get the days until week one ends
  25.     $daysUntilWeekOneEnd = 6 - date('w', $firstDayOfMonthTime);
  26.  
  27.     // Create an array showing the numerical day of hte month when the week ends
  28.     $weekEnd = array();
  29.     $weekEnd[] = $daysUntilWeekOneEnd + 1;
  30.     $weekEnd[] = $daysUntilWeekOneEnd + 8;
  31.     $weekEnd[] = $daysUntilWeekOneEnd + 15;
  32.     $weekEnd[] = $daysUntilWeekOneEnd + 22;
  33.     $weekEnd[] = $daysUntilWeekOneEnd + 29;
  34.  
  35.     // Loop through the week end numbers until we find the week we are on
  36.     foreach ($weekEnd as $index => $end) {
  37.         if ($dayOfMonth <= $end) {
  38.             // Then return that week plus one, because the array is 0-indexed
  39.             return ($index+1);
  40.         }
  41.     }
  42.  
  43.     // If we got this far something went wrong. Return false
  44.     return false;
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement