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

When placed within a setInterval loop, the event.clientY variable becomes inaccessible

I am working on a script to move an element around a web page, and I have encountered a problem. Whenever I try to put it in a loop using setInterval while the mouse is down and moving, I receive an error message stating 'Uncaught TypeError: Cannot re ...

Exploring React Native Networking using react-native-router-flux

Hello everyone, I have a quick query. I am looking to assign each Button to a different page. import React, { Component } from 'react'; import { ActivityIndicator, FlatList, Text, View, TouchableOpacity } from 'react-native'; export ...

Using a custom font with Next.js and Tailwind: Font applied successfully but not displaying correctly

In my project with Next.js (9.4.4) and Tailwind.css (1.4.6), I am incorporating a custom font named SpaceGrotesk. To ensure its functionality, I stored the font files in public/fonts/spaceGrotesk, and then adjusted my configurations as below: // next.confi ...

Tips for emphasizing the letters of the alphabet used in search functionality with Angular

Is there a way to highlight specific alphabets in the searched list instead of highlighting the entire word? Currently, when filtering the memberOffice and memberFacilities lists based on the alphabet entered in the search field, the entire text is highlig ...

Issue with React Google Maps Api: Error occurs while trying to access undefined properties for reading 'emit'

I'm trying to integrate a map using the google-map-react API, but I keep encountering the following error: google_map.js:428 Uncaught TypeError: Cannot read properties of undefined (reading 'emit') at o.r.componentDidUpdate (google_map.js: ...

Changing a transparent div with overlays into a visual representation of its underlying background

I am curious to know if it is feasible to carry out the operation mentioned, given that JavaScript doesn't currently have access to the contents of certain objects, such as a Flash video player. I have explored various screenshot plugins, but none of ...

Pop-up with a unique MediaBox design

Last week, I inquired about window pop-ups and have been brainstorming alternatives. One idea I had is to use mediabox/lightbox style pop-ups. Would it be feasible to create a link that opens a mediabox window off to the side when clicked? Users could dra ...

Stop all file uploads using jQuery

I have integrated the jQuery File Upload plugin () into my website for image uploads. Here is my code snippet: $('#fileupload').fileupload({ url: 'server/index.php', dataType: 'json', dropZone: $('#dropzone&a ...

Converting data into a multidimensional array in AngularJS: A comprehensive guide

Struggling to convert a JSON array into a multidimensional array, looking for some guidance. I attempted using _.groupBy in underscore.js, but it's not proving successful with the nested array. If there is any way to convert from the given data [{ ...

Storing the current date() in JSON format using AngularJS

I am currently working on saving various data, including the current date, in a JSON file stored in LocalStorage. While I have been successful in saving the data, the date is saved in the ISO 8601 format: [{"date":"2014-10-13T17:55:32.953Z"}] This format ...

Identifying specific text enclosed within tags in an external file using PHP

I recently started learning about php, and I am looking for a script that can identify text between specific tags in an external file. I came across a solution here that extracts the text within tags from a given string. However, I am unsure how to mo ...

Is there a way for me to extract the document title from firebase?

I have been trying to use this component to retrieve data, but I am encountering an issue where I cannot fetch the name of the document "sampleCloudFunction" under CloudFunctionMonitor (see image) from the database and display it. Using docRef.id does not ...

Switching the navigation menu using jQuery

I am looking to create a mobile menu that opens a list of options with a toggle feature. I want the menu list to appear when the toggle is clicked, and I also want to disable scrolling for the body. When the toggle menu is clicked again, the list should c ...

Is there a way to verify the href attribute and potentially append the complete URL address if necessary?

Is there a way to verify the href attribute and replace it with a full URL if it doesn't contain the full path? I tried using JavaScript for this, but it doesn't seem to work on IE 8. This is my JavaScript code: fullUrl = $(this).filter('[ ...

Exploring the power of Next.js dynamic routes connected to a Firestore collection

Currently seeking a solution to create a dynamic route that will display each document in a Firestore collection using Server-side Rendering. For instance, if there is a document named foo, it would be accessible at test.com/foo under the [doc] page compo ...

Using the Count() function in PHP to update information upon page refresh

I have created a basic cart that displays a div containing purchased items when hovered over. The issue I am facing is that every time I click on the add to cart button, it doesn't immediately update the number of items in the cart. I have to manually ...

Sleek dialog sliding animation with Svelte

I'm struggling with a svelte component that I have and I'm trying to implement a slide down animation when it closes. The slide up animation is functioning correctly, but for some reason the slide down animation is not working. Does anyone have a ...

Here is an example of how to use a script tag to check the value of a select tag in HTML:

Hi there! I'm working on a piece of code where I need to retrieve the selected value from a dropdown menu in an HTML select tag and display it in the element with the id='h1' at the bottom. The script tag is already included within the head ...

Error: Oops! The super expression can't be anything other than null or a function in JavaScript/TypeScript

I am facing an issue with class inheritance in my code. I have a class A that extends class B, which in turn extends class C. Whenever I try to create a new instance of class A within a function, I encounter the following error message: Uncaught TypeError: ...

Tips for choosing specific characters from a string using JavaScript

When dealing with URL strings like "example.com/Apps/Visitor/visitscanner" , "example.com/Apps/Seatings/visitscanner I am interested in extracting the directory name following the "http://example.com/Apps/" For the above examples, if the URL string is " ...