Issue encountered while attempting to adjust a date (the modification was incorrect)

I am currently working on developing a calendar feature using Angular. Part of this project involves implementing drag and drop functionality to allow users to move appointments from one day to another.

However, I have encountered a strange issue. When attempting to move an appointment from April 1st to March 31st, the date gets changed to March 1st instead.

After dropping the appointment, I trigger a change event with the updated schedule data and new day:

drop(evt) {
    let schedule: Schedule;
    schedule = evt.data.schedule;

    // Emit change
    this.scheduleChange.emit({schedule, day: this.day});
  }

Subsequently, I handle the appointment update in the following function:

  scheduleChanged(evt) {
    const schedule = this.createScheduleFromObject(evt.schedule);
    const day = evt.day;

    console.log(day);

    if (this.isSameDate(schedule.start, schedule.end)) {
      schedule.start.setDate(day.getDate());
      schedule.start.setMonth(day.getMonth())
      schedule.start.setFullYear(day.getFullYear());

      schedule.end.setDate(day.getDate());
      schedule.end.setMonth(day.getMonth());
      schedule.end.setFullYear(day.getFullYear());
      console.log(schedule);
    }
  }

It appears that the issue lies in the object transformation to a Schedule class within the following function:

 createScheduleFromObject(obj: any) {
    const schedule: Schedule = Object.assign(new Schedule(null, '', '', '', new Date(), new Date()), obj);
    console.log(obj.start);
    schedule.start = new Date(obj.start);
    schedule.end = new Date(obj.end);
    console.log(schedule.start);

    return schedule;
  }

The output of the console log confirms that the correct date is being returned by this function:

2020-04-01T21:31:49.640Z
Wed Apr 01 2020 23:31:49 GMT+0200

However, when modifying it in the scheduleChanged function, even with the correct date in the console log as March 31st:

Tue Mar 31 2020 00:00:00 GMT+0200

The start date of my schedule ends up being set to:

Sun Mar 01 2020 23:33:19 GMT+0100

This discrepancy raises the question - why is this happening?

Answer №1

It seems like this question is similar to Javascript setMonth shows improper date. The issue in your situation is likely due to setting a date in April to March 31, which doesn't exist and causes it to roll over to the next month.

When updating the values of a date one by one, there can be problems if the initial date does not match the month being adjusted. To avoid this, update all values at once instead of separately:

schedule.start.setFullYear(day.getFullYear(), day.getMonth(), day.getDate());

In the case of moving a date from April 1 to March 31:

  1. The date for April is changed to 31, leading to it rolling over to May 1
  2. The month is reset to March
  3. Year can be adjusted accordingly

By setting the values together, you prevent such issues. For example:

  1. (2020-04-01).setFullYear(2020, 2, 31) -> 2020-03-31

When adjusting the year, consider setting the month and day as well. Similarly, when modifying the month, include adjustments to the day. This approach applies to time adjustments too, ensuring consistency across different units of time.

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

What is the best way to prevent excessive rerenders when verifying if database information has been successfully retrieved?

Hey there, I'm encountering an issue where the if statement check in my code is causing a "too many rerenders" problem. I'm trying to create a delay between pulling data from the database and calculating the BMI. Any suggestions on how to resolve ...

What is the method to extract a value from the $emit payload using Vue.js?

I have a situation where I am sending an event with different values from my ConversationList component (child) to the ConversationModel component (parent). Conversation List getConversation(conversation_id, receiver_id, username, avatar){ this.$emit(& ...

Electronic circuit embedded within a material-textured text field offering multiline functionality

While experimenting with TagsInput, I came across this helpful snippet on codesandbox that you can check out here. The challenge I encountered is when there are numerous chips, they extend beyond the boundaries of the text field. My goal is to implement ...

The image fails to display correctly

As I work on creating a basic webpage in HTML and JavaScript, my goal is to validate certain parameters (such as width, height) of an image that users upload via a form. In JavaScript, I extract the file from the form and attempt to display it as an image ...

The ng-model directive in Angular is effective for handling arrays, however, it may not

The implementation of the ng-model directive seems to be incomplete when dealing with string values in JavaScript. However, by using a list of dictionary objects and looping through them with ng-repeat, this issue is resolved. One reason for this behavior ...

Error in Angular Services due to Circular Dependency

I am encountering the following error message: Provider parse errors: Cannot instantiate cyclic dependency! Within my code, I have a Component dedicated to making HTTP calls to my backend server: backend.component.ts import { Http } from '@angul ...

Unable to refresh the fullcalendar section following an ajax post click

Currently developing a calendar using fullcalendar. I have created an ajax button that retrieves events from another php page. The first click on the ajax button works fine, displaying a nice month calendar with events. However, my issue arises when I cl ...

Angularjs - How come I am able to modify an object but not the list (ng-repeat) from a separate view?

After updating the customers object in the console, I noticed that the list (ng-repeat) is not reflecting the changes. What should I do? Interestingly, it works fine when I implement this function and view2.htm's HTML inside page.htm. HTML "page.htm" ...

Exploring the Realm of Angular Controllers and Services: Embracing Triumphs and

Currently in the process of creating a service layer for an existing web app using Angular. I am transitioning $http requests and data manipulation to custom Angular services. While I have a good understanding of Dependency Injection in services, I am enco ...

Angular's onreadystatechange event is triggered when the state

Hey there, I'm new to Angular and had a question. Is it possible to use the $http service in Angular to trigger a function whenever there is any change in the ready state/status, not just for success or failure? If so, what would be the equivalent ang ...

I continue to encounter the same error while attempting to deliver data to this form

Encountering an error that says: TypeError: Cannot read properties of null (reading 'persist') useEffect(() => { if (edit) { console.log(item) setValues(item!); } document.body.style.overflow = showModal ? "hidden ...

Comparing JS Async/Await, Promise, and Callbacks: Which is Best

I'm trying to wrap my head around the differences between callbacks, promises, and async/await. While I understand how callbacks and promises work, I'm struggling with grasping the usage of async/await. I know it's essentially a syntactic su ...

AngularJS: Modifying values in one div updates data in all other divs

The webpage appears as shown below: HTML <li class="list-group-item" ng-repeat="eachData in lstRepositoryData"> <div class="ember-view"> <div class="github-connection overflow-hidden shadow-outer-1 br2"> <!-- ...

Launch a YouTube video within a sleek and stylish Bootstrap modal popup

I am currently extracting video data from my SQL table. The fields in the table are as follows: - sidebar_video_id (auto increment) - sidebar_video_nev - sidebar_video_link (full URL) - sidebar_video_v_id (video ID at the end of the URL) What I'm tr ...

Incorporating additional properties into a TypeScript interface for a stateless, functional component within a React Native application

When following the React Native documentation for consistent styling, a recommendation is made to create a <CustomText /> text component that encapsulates the native <Text /> component. Although this task seems simple enough, I'm facing d ...

Explain the functioning of the Node.js event loop and its ability to manage numerous requests simultaneously

Recently, I delved into testing asynchronous code in node.js. From what I understand, when there is an asynchronous operation taking place, Node.js should be able to handle new requests. Below is a snippet of code I wrote using express and axios: app.get(& ...

Retrieving data from a JSON file at 10-minute intervals with Ajax and visualizing it on Google's globe API

After downloading Armsglobe, a globe API provided by Google to draw lines in countries using their names, I noticed that the original code does not fetch JSON data periodically. I attempted to use a simple setTimeout() function in dataloading.js to address ...

Tips on utilizing index and eliminating React Warning: Ensure every child within a list has a distinct "key" prop

Hello, I am encountering an issue where I need to properly pass the index in this component. Can you help me figure out how to do that? Error: react-jsx-dev-runtime.development.js:117 Warning: Each child in a list should have a unique "key" prop ...

The Angular promise refuses to resolve at my desired time

I am struggling with managing Angular promises in order to control when they resolve. In the code snippet below, my intention is to first retrieve KeyDataFromServer() and then proceed with executing the remaining commands only after all the keys have been ...

Behavior of Shadow DOM role when using the <a> element without an href attribute

Recently, I started working with the shadow DOM and encountered a strange issue: In my Ionic Angular application, there is a text styled like a link in this form (simplified): <a href="${ifDefined(this.href)}">link</a> When testing ...