Last month's display is currently unidentified

function calculateTime() {
    var Make_It_12_Hour = true;
    var currentTime = new Date();
    var hour1 = currentTime.getHours() - 1; 
    var hour2 = currentTime.getHours();
    var hour3 = currentTime.getHours() + 1;
    var minutes = currentTime.getMinutes();
    var minute1 = currentTime.getMinutes() - 1;
    var minute2 = currentTime.getMinutes();
    var minute3 = currentTime.getMinutes() + 1;

    if (Make_It_12_Hour) {
        hour1 = hour1 % 12;
        hour1 = (hour1) ? hour1 : 12;
        hour2 = hour2 % 12;
        hour2 = (hour2) ? hour2 : 12;
        hour3 = hour3 % 12;
        hour3 = (hour3) ? hour3 : 12;

        if (hour1 < 0)  hour1 = "11";
        if (hour3 > 12) hour3 = "1";
        if (hour1 < 10) hour1 = "0" + hour1;
        if (hour2 < 10) hour2 = "0" + hour2;
        if (hour3 < 10) hour3 = "0" + hour3;
        if (minute1 < 0) minute1 = "59";
        if (minute3 > 59) minute3 = "1";
        if (minute1 < 10) minute1 = "0" + minute1;
        if (minute2 < 10) minute2 = "0" + minute2;  
        if (minute3 < 10) minute3 = "0" + minute3;
    } else {
        if (minute1 < 0) minute1 = "59";
        if (minute3 > 59) minute3 = "1";
        if (minute1 < 10) minute1 = "0" + minute1;
        if (minute2 < 10) minute2 = "0" + minute2;
        if (minute3 < 10) minute3 = "0" + minute3;
        if (hour1 < 0) hour1 = "23";
        if (hour3 > 23) hour3 = "0";
        if (hour1 < 10) hour1 = "0" + hour1;
        if (hour2 < 10) hour2 = "0" + hour2;
        if (hour3 < 10) hour3 = "0" + hour3;  
    }

    document.getElementById("time1-1").innerText = hour1;
    document.getElementById("time1-2").innerText = hour2;
    document.getElementById("time1-3").innerText = hour3;
    document.getElementById("time2-1").innerText = minute1;
    document.getElementById("time2-2").innerText = minute2;
    document.getElementById("time2-3").innerText = minute3;
}

function calculateDate() {

    var months = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"); 
    var currentTime = new Date();
    var day1 = (currentTime.getDate() - 1).toString();
    var day2 = currentTime.getDate().toString();
    var day3 = (currentTime.getDate() + 1).toString();
    var month = currentTime.getMonth();

    if (day1.length == 1) day1 = "0" + day1;
    if (day2.length == 1) day2 = "0" + day2;
    if (day3.length == 1) day3 = "0" + day3;

    document.getElementById("date1-1").innerText = months[month - 1];
    document.getElementById("date1-2").innerText = months[month];
    document.getElementById("date1-3").innerText = months[month + 1];
    document.getElementById("date2-1").innerText = day1;
    document.getElementById("date2-2").innerText = day2;
    document.getElementById("date2-3").innerText = day3;
}

calculateTime();
calculateDate();
setInterval(calculateTime, 2000);
setInterval(calculateDate, 60000);

Hello there! The above code is functioning correctly. It displays the current and next month, but there is an issue with this line producing 'undefined':

 document.getElementById("date1-1").innerText = months[month - 1];

I am uncertain about what is causing this. By changing the line from -1 to +1, it shows the current month.

You can find the full code in jsfiddle.

Answer №1

To get the current month in JavaScript, you can do the following:

var month = currentTime.getMonth();

Keep in mind that months are 0-based in JavaScript, so January is represented as 0.

If you try to access the array months at index month - 1, you will end up with -1 since it's currently January. This will lead to months[-1] returning undefined.

To handle this situation, you can use the modulo operator (inspired by a solution from another Stack Overflow question):

months[(((month - 1) % 12) + 12) % 12]

Alternatively, if you have added the modulo function to the Number prototype as in the other example:

months[(month - 1).mod(12)]

For instance, if month = 0, then months[11] is what you would obtain.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

To enable the standard PayPal 'donate' button functionality, you can remove the submitHandler from jQuery Validate dynamically

I need to insert a PayPal donate button into the middle of an AngularJS donation form, specifically by nesting the PayPal generated form tags within the donation form tags. This donation form is utilizing an older version (1.12) of jQuery Validate, which ...

Due to a glitch in the firebase cloud function, the payment is not going through

I have developed a react-redux application with Firestore as the database and now I want to integrate Firebase Cloud Functions to handle Stripe payments. Here is how it's set up: Below is the action method for checkout, which processes token and amo ...

To open a popup menu with a text box, simply click on the text box

Whenever the text box text is clicked, a popup menu should open with a text box. Similarly, when the filter icon in the right side corner is clicked, a menu should open with a list of checkboxes. However, currently both menus are opening when clicking on b ...

Locate and extract the JSON object using the specified key-value pair

Trying to extract a specific object from a complex json file, noting the key, and then returning a new json poses a challenge. I am using expressjs as the backend for this task. Sample.json '[{"ServID":"Rai 1","Parametri" ...

How to detect internet connection in any screen using React Native?

I'm facing confusion regarding how to display my customDialog when there is no Internet connection in my app. Currently, I have successfully shown my customDialog only in the LoginScreen. However, I want to display it from different screens, not just ...

I keep running into errors whenever I try to run npm install in my React JS project. The only way for me to successfully install dependencies is by using npm install --force. How can I go about resolving these

I am encountering this error message while working on my project: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: @mui/<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="681b1c11040d1b ...

Attempting to invoke a function containing a promise in Javascript

Calling the function numberOfRedeems(dealId) from another function named setUpData raises an issue where the numberOfRedeems() function, which includes a promise and returns "counter", always returns as undefined when executed within the setUpData function ...

Add fresh inline designs to a React high-order component creation

Applying a common HOC pattern like this can be quite effective. However, there are instances where you may not want a component to be wrapped, but rather just extended. This is the challenge I am facing here. Wrapper HOC const flexboxContainerStyles = { ...

Programmatically link an Angular JS model to a template using binding

When given an HTML template like the following: <div class="info"> <div class="title"><a href="property-detail.html">{{title}}</a></div> <div class="location">{{location}}</div> <div class="property ...

Issue with Firebase V9 addDoc: No indication of success or failure, and data is not being written to the

I am encountering an issue where the authentication related functions are working fine, but I am unable to make any progress with Firestore. Despite no errors or successes being returned by the try-catch block, nothing seems to happen in the Firestore data ...

Direction of Scrolling

Is it possible to have a div move in the opposite direction of mouse scroll, from the top right corner to the bottom left corner? Currently, it is moving from the bottom left to the top right. #block { position: absolute; top: 400px; left: 100px; < ...

What is causing the error to occur during the installation of the NestJS Client?

Encountered an error while attempting to install the nestjs client, and I'm completely puzzled by this issue. PS C:\Users\meuser> npm i -g @nestjs/cli npm ERR! code ETARGET npm ERR! notarget No matching version found for @angular- ...

AngularJS - "Refrain from replicating items in a repeater"

I am facing an issue with creating HTML textarea elements for each member of an array. Despite consulting the AngularJS documentation and attempting different track by expressions, I am unable to render them. The problem arises when a user inputs the same ...

When combining stores, what sets Mobx.inject apart from Mobx.observer?

As I start integrating my store with mobx, a question arises in my mind. What sets apart the usage of observer(['store'],...) from inject('store')(observer(...))? Upon closer examination, it seems that inject is not reactive. So, what ...

Using jquery to navigate back to the search results page

I am trying to figure out how to use jquery to return to the search results page, but my current code always takes me back to the main data instead of the search results. Can anyone help me with this issue? $(document).ready(function() { $("#kembali ...

Invoke actions when clicking outside of components

Currently, I have a HeaderSubmenu component that is designed to show/hide a drop-down menu when a specific button is clicked. However, I am now trying to implement a solution where if the user clicks anywhere else in the application other than on this drop ...

Call upon the prototype method of the parent class

"I'm having trouble understanding a piece of my code: //constructor function Widget (options) { }; //return the string Widget.prototype._addEditFormString = function (val) { return "<in ...

I would like for my element to increase and decrease in size while rotating when the button is clicked

I am trying to create an element that changes its size while spinning when a button is clicked. It seems to be working fine on hover, but not onclick. Here is the code I have: <div class="rec">Rec</div> <button id="button&quo ...

What is the best way to manage zoom settings following a completed search query?

Whenever I try to search for an address using this map, it zooms in way too much making the map unusable. Despite my efforts to adjust the map bounds, I have not been successful. It seems like I am on the right track but for some reason, it just isn't ...

Incorporate Object names and Variable names in Javascript programming

I have an object named res and a variable named lea. I need to concatenate. For example: let lea = "abc"; let res = { abc:'steve' }; console.log(res.lea); So my output should be steve. I tried it like this: console.log(res.`${lea}`); ...