Отображение getMonth после декабря не определено

#javascript #date

#javascript #Дата

Вопрос:

У меня есть текст с указанием дня и следующих месяцев и т.д. Но в декабре я не могу вспомнить январь.

 <body onload="displayDates()">
  
    <!--dropdown ville-->
    <div class="dd">
        <h3 style="font-family: 'Open Sans', sans-serif;font-size:1.1em;color:#54595f; font-weight:400;">For EACH friend who signs up until <span id="currentMonth"></span> <span id="lastThursday"></span>, you’ll get a FLEX PASS which will allow you to enjoy unlimited trips with the first the 30 minutes free for a whole month, starting on <span id="nextMonth"></span> 1.</h3>
        <h3 style="font-family: 'Open Sans', sans-serif;font-size:1.1em;color:#54595f; font-weight:400;">Get a second FLEX PASS starting <span id="inTwoMonths"></span> 1 if you refer a second friend and so on if you refer more friends. The more friends who sign up, the more FLEX PASSES you’ll receive!</h3>
    </div>

    <div id="demo"></div>

</body>

<script>
    //Declare variables
    var month;
    var year;
    var numberOfDays;

    //Dynamic text to be replaced
    var currentMonthText = document.getElementById("currentMonth");
    var lastThursdayText = document.getElementById("lastThursday");
    var nextMonthText = document.getElementById("nextMonth");
    var inTwoMonthsText = document.getElementById("inTwoMonths");
    

    //Weekdays and months
    var weekdays = [ "Sun", "Mon", "Tue", "Wed", "Thurs", "Fri", "Sat" ];
    var monthsName = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];
    

    //How many days are in this month
    //1. Get the current month
    function daysInMonth (month, year) { 
        return new Date(year, month, 0).getDate(); 
    }

    function displayDates() { 
        var date = new Date();

        //Today's date number
        var stringDate = date.toString();
        var todayDate = stringDate.slice(8,10);
        //console.log(stringDate);

        var lastThursday; 
        var nextLastThursday;
        month = date.getMonth()   1;
        year = date.getFullYear() ;
        numberOfDays = daysInMonth(month, year);

        //Find the last thursday of current month
        for (var i = 1 ; i < numberOfDays ; i  ) {

            //Create a new date
            var newDate = new Date(year,month - 1,i,0,0,0,0);
            //console.log("newDate "   newDate);
            var newDay = newDate.getDay();
            //console.log("newDay "   newDay);
            
            if (newDay == 4) {
                //console.log(newDate);
                var string = newDate.toString();
                lastThursday = string.slice(8,10);
            }

        }

        //Display info dynamically
        currentMonthText.innerHTML = monthsName[month - 1];
        lastThursdayText.innerHTML = lastThursday;
        nextMonthText.innerHTML = monthsName[month];
        inTwoMonthsText.innerHTML = monthsName[month   1]

        //Check if date to register has passed, if so show next month
        var pastDate = parseInt(lastThursday);
        var nextDate = parseInt(todayDate);

        if (pastDate < nextDate) {
            console.log("past date");

            //Find the last thursday of current month
            for (var i = 1 ; i < numberOfDays ; i  ) {

                //Create a new date
                var newDate = new Date(year,month,i,0,0,0,0);
                //console.log("newDate "   newDate);
                var newDay = newDate.getDay();
                //console.log("newDay "   newDay);

                if (newDay == 4) {
                    //console.log(newDate);
                    var string = newDate.toString();
                    nextLastThursday = string.slice(8,10);
                }

            }

            //Display info dynamically
            currentMonthText.innerHTML = monthsName[month];
            lastThursdayText.innerHTML = nextLastThursday;
            nextMonthText.innerHTML = monthsName[month   1];
            inTwoMonthsText.innerHTML = monthsName[month   2]

        }
    }

</script>
 

Комментарии:

1. Вы присваиваете своей переменной month значение, .getMonth() 1 поэтому в декабре это будет 12 (месяцы проиндексированы на 0), что выходит за пределы диапазона вашего monthsName массива. Вам нужно вернуть индекс обратно к 0 либо с помощью условного, либо с использованием модуля. month = date.getMonth() 1 > 11 ? 0 : date.getMonth() 1; или month = (date.getMonth()%monthsName.length)

Ответ №1:

В комментарии Пилчарда есть ваш ответ (вы превышаете длину массива monthsName, поэтому используйте month = (date.getMonth()%monthsName.length) ), так что это действительно просто длинный комментарий. Надеюсь, комментарии в коде объясняют, что происходит.

Код может быть намного проще, если вы используете toLocaleString с параметрами (например {month: 'long'} ) для форматирования даты и короткими функциями для добавления дней и месяцев.

 function updateDates() {
  let d = new Date();
  // Get end of month
  let eom = new Date(d.getFullYear(), d.getMonth() 1, 0); 
  // Get last Thursday in month
  let lastThuInMonth = new Date(eom);
  lastThuInMonth.setDate(eom.getDate() - ((eom.getDay() - 4   7)%7));
  // Get next and following months
  let nextMonth = new Date(d.getFullYear(), d.getMonth() 1, 1);
  let nextMonth2 = new Date(d.getFullYear(), d.getMonth() 2, 1);
  // Simple functions to format dates as required
  let getMonthStart = d => d.toLocaleString('default', {day: 'numeric', month: 'long'});
  let dateTimestamp = d => d.toLocaleString('default', {day: 'numeric', weekday:'short', month: 'short'});
  // Update document
  document.getElementById('lastThursday').textContent = dateTimestamp(lastThuInMonth);
  document.getElementById('nextMonth').textContent = getMonthStart(nextMonth);
  document.getElementById('inTwoMonths').textContent = getMonthStart(nextMonth2);
}

window.onload = updateDates; 
 <h3 style="font-family: 'Open Sans', sans-serif;font-size:1.1em;color:#54595f; font-weight:400;">For EACH friend who signs up until <span id="lastThursday"></span>, you’ll get a FLEX PASS which will allow you to enjoy unlimited trips with the first the 30 minutes free for a whole month, starting on <span id="nextMonth"></span>.</h3>
    <h3 style="font-family: 'Open Sans', sans-serif;font-size:1.1em;color:#54595f; font-weight:400;">Get a second FLEX PASS starting <span id="inTwoMonths"></span> if you refer a second friend and so on if you refer more friends. The more friends who sign up, the more FLEX PASSES you’ll receive!</h3>