JavaScript Calendar lacks two days

I'm currently developing a custom calendar application using Javascript with Vue JS. One of the methods I've created is for getting the number of days in a specific month:

daysInYearMonth(y,m){
  return new Date(y, m, 0).getDate()
}

When I log the result of this method for July, I correctly get 31 days. However, when I try to use this value in my calendar:

this.days = [...Array(this.daysInYearMonth(this.year, 
  this.month)).keys()]
}

Surprisingly, the console logs only 29 days, which is two days short. Simply adding those two days messes up the other months. You can view my code on CodePen.

Just a heads up, my team has opted not to use Moment.js and instead focus on Vue and plain JavaScript, which presents its own set of challenges.

Answer №1

daysInYearMonth() calculates the number of days in the previous month instead of the current one. This is because using day 0 in a date signifies the last day of the month prior to it. Hence, for July, you will get 30 instead of 31. To obtain the last day of the current month, you should consider the next month.

daysInYearMonth(y,m){
  return new Date(y, m+1, 0).getDate()
}

Another issue arises from the fact that array indices start at 0, while days in a month start at 1. Consequently, using

Array(this.daysInYearMonth(this.year, this.month)).keys()
yields an array from 0 to 30 rather than from 1 to 31. The solution is to implement a loop that begins at 1, instead of manipulating arrays.

let lastday = this.daysInYearMonth(this.year, this.month);
this.days = [];
for (let d = 1; d <= lastday; d++) {
    this.days.push(d);
}

Answer №2

  • Let's start with the first point:

Instead of using

return new Date(y, m, 0).getDate()
, consider using m + 1, as 0 represents the last day of the previous month. For more information, refer to this resource.

  • Moving on to the next point:

Remember that this.days starts from zero, but the actual days in a month are not zero-based. Therefore, your count should range from 0 to 30 rather than 1 to 31.

I trust this explanation clarifies things for you. Regards

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

How to search for a value in Firebase database and save it to an HTML table?

I am working on fetching specific values from my 'snapshot' and storing them if they exist. Below is the snippet of my code: function paydata(){ firebase.database().ref("pay/0/0/").once('value', function(snapshot){ var resp ...

Tips for sending event and additional arguments to a click handler

Hi there, I recently created a canvas using easelJS. Within my canvas, I have points that have a click handler defined for them with this syntax: p.on("click", handleMouseClickEvent); However, I am facing an issue when trying to pass arguments to the han ...

Angular 2, React, or any other modern framework.getList()?.map

I have experience working on multiple angular 1 projects and I absolutely enjoyed it. We have several upcoming projects where I need to recommend JavaScript frontend libraries/frameworks. With the decline of angular 1 and mixed reviews about angular 2&apos ...

Delayed Page Update: Click Event Doesn't Execute Correctly Without JQuery

I'm a beginner in JavaScript and unable to use JQuery I have a table and I want to highlight the selected row on the click event. At the same time, I need to change the value of an input field. However, when I click on a row, the highlight effect get ...

Unexpected behavior encountered when running Angular 8 radio button checked function

I have an Angular 8 web app with some unique logic implemented as shown below: HTML: <div *ngFor="let item of selectedItems;"> <input type="radio" [(ngModel)]="mySelectedItem" [value]="item.key" (ngModelChange)="setCh ...

What is the best way to insert a variable into a nested component in Vue.js?

I am currently working on an app that has nested components. The app is triggered by the filter id. Within the app, there is a data element called minTotalSpent which is currently set to "3". The first placement on the page is displaying correctly. Howev ...

The nuSelectable plugin enhances the functionality of jQuery

I am currently experimenting with the jQuery nuSelectable plugin in order to enable users to select multiple items simultaneously. Unfortunately, I am encountering difficulties in making the selection work as intended. You can find the plugin here. After ...

Incorporate text onto an image using Semantic UI

Currently, I am utilizing Semantic UI to display images. While it is functioning well for me in terms of adding text near the image, I desire to have the text positioned on top of the image. Ideally, I would like it to be located on the lower half of the i ...

Issue encountered while loading JSON data into DynamoDB's local instance

I have successfully set up DynamoDB local and everything is functioning as expected after going through their documentation. I have also tested their example code, which worked flawlessly. The Users table has been created with the name "Users". Below is ...

The typescript error TS2339 is triggered by the property 'webkitURL' not being found on the 'Window' type

Currently utilizing Angular 2 in a project that is compiled with TypeScript. Encountering an issue when attempting to generate a blob image: Error TS2339: Property 'webkitURL' does not exist on type 'Window' The TypeScript code causi ...

The counter unexpectedly increments by 2 instead of 1

I'm attempting to create a counter that increases by one each time according to the code snippet below: var imnum = 0; (function changeImage() { ++imnum; $( ".slider" ).fadeOut(5000, function() { $('#home-slider-im').attr("s ...

Infinite dice roller for a six-sided die

Looking for assistance with a School JavaScript assignment focusing on creating a 6-sided dice roller program? Need some guidance on how to approach this task? The program should allow users to choose how many dices to roll, ranging from 1 to 5. The sum o ...

Is it feasible to activate a Bootstrap Tooltip from a different element?

I am currently developing a system that enables users to add notes over an image they upload. Presently, I have a note div that, upon clicking, opens a text box for editing. When hovering over this div, I utilize Bootstrap Tooltip to preview the contents o ...

A URL that quickly updates live content from a backend script

As a beginner, I am seeking guidance as to where to start on my journey of learning. I need assistance in creating a script that can efficiently fit within a small URI space and constantly updates itself with information from a server script. My target bro ...

Steps for generating instances of an HTML page and dynamically adding them to a list on the main page

I have a main HTML page and I need to insert a dynamically generated list from a template in another HTML file that I created. The template for each item in the list is located on a separate HTML page. My goal is to create multiple instances of this HTML ...

Combining numerous base64 decoded PDF files into a single PDF document with the help of ReactJS

I have a scenario where I receive multiple responses in the form of base64 encoded PDFs, which I need to decode and merge into one PDF file. Below is the code snippet for reference: var pdf_base1 = "data:application/pdf;base64,JVBERi0xLjQKJfbk/N8KMSAwIG9 ...

Displaying VueJS property inside an array of HTML elements

Currently, I am working with an HTML array that contains the following data: data-groups='["category_all", "data goes here"]' In my project, there is a prop named "title" that holds the specific string needed to be displayed in the "data goes he ...

Displaying a list of data separately in rows using React JS

I am encountering an issue with React Js. I need to display names data in individual rows. const names = ['James', 'John', 'Paul', 'Ringo']; Here is my code: return ( <div class="col-lg-8 bar-name"> ...

Discover the convenient shortcut keys that enable you to easily align text in editors, similar to the functionality found in

When working in MS Office, aligning text is done by selecting the text and then using the shortcut keys Ctrl+L for left align, Ctrl+R for right align, and Ctrl+E for center alignment. However, when using online text editors like TinyMCE and CKEditor, I am ...

How can I vertically align a photo or image on Facebook?

Can anyone explain how Facebook manages to vertically align its photos without using padding or margins? I've looked into their img tag and its parent, but neither seem to have any spacing properties. Although there is a vertical-align attribute prese ...