Search code examples
javascriptjqueryasp-classicdayofweek

Is there an easy way to find the last date a day of week occurs in the current month


I am trying to display the date of the last Wednesday in the current month... so that it will automatically change to the correct date when the next month occurs. (So instead of having to say: "Performing the last wednesday of every month", I can dymanmically give the actual date.)

For example, I would want the date to show on the webpage as Wednesday, Sept 25th for this month, and then appear as Wednesday, Oct 30th next month.

A bonus additional solution would be if I could get the next month's date to display after the previous date has past. In my above example, when the current date is Sept 26-30 (any date after that last wednesday, but still in the same month).. the date would show the next performance date of Oct 30th.

It would be great if the solution was through html, javascript/jquery or asp.

Thanks, SunnyOz


Solution

  • It depends on your criteria for "easy". Here's a simple function to do as required, it's 5 lines of working code that can be reduced to 4, but will lose a bit of clarity if that's done:

    function lastDayInMonth(dayName, month, year) {
      // Day index map - modify to suit whatever you want to pass to the function
      var dayNums = {Sunday: 0, Monday:1, Tuesday:2, Wednesday:3, 
                     Thursday:4, Friday:5, Saturday:6};
    
      // Create a date object for last day of month
      var d = new Date(year, month, 0);
    
      // Get day index, make Sunday 7 (could be combined with following line)
      var day = d.getDay() || 7;
    
      // Adjust to required day
      d.setDate(d.getDate() - (7 - dayNums[dayName] + day) % 7);
    
      return d;
    }
    

    You can change the map to whatever, just determine what you want to pass to the function (day name, abbreviation, index, whatever) that can be mapped to an ECMAScript day number.

    Edit

    So in the case of always wanting to show the last Wednesday of the month or next month if it's passed:

    function showLastWed() {
      var now = new Date();
      var lastWedOfThisMonth = lastDayInMonth('Wednesday', now.getMonth()+1, now.getFullYear());
      if (now.getDate() > lastWedOfThisMonth().getDate()) {
        return lastDayInMonth('Wednesday', now.getMonth()+2, now.getFullYear());
      } else {
        return lastWedOfThisMonth;
      }
    }
    

    Note that the function expects the calendar month number (Jan = 1, Feb = 2, etc.) whereas the getMonth method returns the ECMAScript month index (Jan = 0, Feb = 1, etc.) hence the +1 and +2 to get the calendar month number.