0

The following PHP function returns the n-th weekday of a month, e.g. the 3rd Wednesday in January 2012 in the form 18-1-2012:

<?php
  function giveNthDay($month, $year, $no, $day) {
     $counter = 0;
     for($i=1;$i<=31;$i++) { //Schleife für 31 Tage
         if(!checkdate($month, $i, $year)) { //wenn datum nicht existiert (bspw. 30. februar) zu nächstem schleifendurchlauf springen
             continue;
         } else {
             if(date('l', strtotime($i.'-'.$month.'-'.$year))==$day) { //wenn generiertes Datum gleicher Wochentag wie gesuchter Tag $day
                 $counter++; //dann $counter um eins erhöhen
                 if($counter==$no) { //falls $counter==$no, also falls bspw. DRITTER ($no==$counter==3) Mittwoch gefunden, Datum zurückgeben
                     return     $i.'-'.$month.'-'.$year;
                 }
             }
         }
     }
     return false; //existiert nicht, bspw. fünfter Sonntag gibt es nicht in jedem Monat
  }
?>

If the date doesn't exist (e.g. 5th Friday in January 2012), it returns false.

This works fine for examples like:

giveNthDay(1, 2012, 3, "Wednesday");
giveNthDay(1, 2020, 3, "Wednesday");
giveNthDay(1, 2031, 3, "Wednesday");

but from

giveNthDay(1, 2038, 3, "Wednesday");

on, it returns false even though every January has more than 3 Wednesdays!

I tried hard to find out what the reason for this strange behaviour is but I can't figure it out. Can anyone help me?

1
  • An if block that just does a continue is really gross. Have you heard of an "else if"? Or maybe the getdate() function? Commented Jan 15, 2012 at 18:31

1 Answer 1

6

2038 is out of scope, max date being 2037 (on a 32 bits architecture). time() is a unix timestamp (starting the 1970-1-1 00:00:00).

Sign up to request clarification or add additional context in comments.

2 Comments

The DateTime class should be used for dates after 2038.
date('c', pow(2,31)); > 2038-01-19T04:14:08+01:00, but my system is 64 bits, so I can grow bigger: echo strftime('%c', pow(2,62)); Tue Jun 19 08:45:04 109626219 Your next server will be able to deal with 2038 I guess.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.