Javascript: Find next nth day of month

Having looked around for code that will find the next, say 4th Wednesday, or the next 5th Sunday, I decided to write my own. The problem is that most solutions I found do not handle the 5th Sunday problem correctly.

This is my solution. First the function:


<script type="text/javascript">
<!-- Begin

var monthName = ["January","February","March","April","May","June", "July", "August","September","October","November","December"];

function showDate(dayOfWeek, weekOfMonth)
// dayOfWeek - the days of the week 0-6, where 0="Sunday".
// weekOfMonth - the week of the month = 1-5
{
  var df = new Date();        // Found date (starts at first day of this month)
  var dt = new Date();        // Today
  var de = new Date();        // End of month
  var foundIt = 0;
  var count = 0;          // Just to ensure we don't get any infinite loops!

  while (!foundIt && count < 10)
  {
    // First day of the month
     df.setDate(1);

     // Last day of month
     de.setDate(1);          // first day of month
    de.setMonth(df.getMonth() + 1);  // go to next month
    de.setDate(de.getDate() - 1);    // and back a day - gives last day of relevant month

      // Desired day of week
      if (dayOfWeek < df.getDay())
        df.setDate(df.getDate() + dayOfWeek - df.getDay() + 7);
      else
        df.setDate(df.getDate() + dayOfWeek - df.getDay());

      // Desired week of month
    df.setDate(df.getDate() + (weekOfMonth - 1) * 7);

    if (df >= dt)
    {
    // Date found is after or equal to today
    if (df <= de)
    {
      // Day is less than or equal to end of month, so... Found it!
          document.write(df.getDate());
          if (df.getDate() == 1)
            document.write("st ");
          else if (df.getDate() == 2)
            document.write("nd ");
          else if (df.getDate() == 3)
            document.write("rd ");
          else
            document.write("th ");
          document.write(monthName[df.getMonth()]);
      foundIt = 1;
    }
    // else
      // Date is after end of this month
      // df is already next month - try again
    }
    else
    {
      // Date is before today
       // Move to next month
      df.setMonth(df.getMonth() + 1);
    }
    count++;
  }
}

//-->
</script>

And then a couple of examples of it in use, firstly, showing the 2nd Saturday, and then the 5th Sunday:


       <th>2<br><script type="text/javascript">
        <!-- Begin
         showDate(6, 2);
        //  End -->
       </script></th>
       <th>5<br><script type="text/javascript">
        <!-- Begin
         showDate(0, 5);
        //  End -->
       </script></th

Leave a Reply

Your email address will not be published. Required fields are marked *