heinriches.com
  • Facebook
  • Programming
    • C#
    • MVC
    • PHP
  • Thoughts
  • WordPress

Next Sunday

Posted on November 22, 2011 by Matt in PHP, Programming
Home» Programming » PHP » Next Sunday

I am currently working on our church website and we have discovered an interesting issue. Our church services changes based on which week the sunday falls under.

Example:

  1. Church is at 10am and 5pm
  2. Church is at 2pm and no evening service
  3. Church is at 10am and 5pm
  4. if last sunday of month then 10am and no evening service else 10am and 5pm
  5. Church is at 10am and no evening service

So how do you figure out how to do this?

PHP has a great function called strtotime. It will take plain english and return a unix timestamp. You then take that date and get it’s week number and divide by 7 and take the ceiling and …. let me just show you the code.

try {
     $nextSunday = strtotime("next sunday");
     $wn = ceil( date( 'j', $nextSunday) / 7 );
     $ldom = mktime(0, 0, 0, (date('m') + 1), 0, date('Y'));

     $diff = round(abs($nextSunday-$ldom)/86400);

     switch ($wn) {
          case 1:
               echo "First Sunday";
             break;
          case 2:
               echo "Second Sunday";
             break;
          case 3:
               echo "Third Sunday";
             break;
         case 4:
              if (diff>=7){
                   echo "Fourth Sunday";
              }else {
                   echo "Last Sunday";
              }
            break;
         case 5:
             echo "Last Sunday";
         break;
       }

     echo "<br />";
   }
     catch(Exception $e) {
     echo($e);
   }

See that makes sense right? Ok it took me a little bit too. Next post I hope to show how to wrap this into a wordpress widget.

Happy Coding

Comments are closed.

Loading...

(c) 2012 heinriches.com - Web Design by Jason Bobich