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 process for retrieving an Object from $cookies?

I've encountered an issue where I'm storing a user object on a Cookie and, upon the client's return visit to the site, I want to utilize this object's properties. However, upon the client's return, my cookie object appears as [obj ...

Is there a way to set up the application that consumes an npm module with a private git url to strictly utilize files exclusively from the module's dist folder?

In my angular application, I encountered an issue with angular-cli not supporting the creation of a library. To work around this, I opted to use the popular git project found at https://github.com/jvandemo/generator-angular2-library for creating my library ...

Converting DateTime to Days in R and calculating the mean value

Seeking to calculate the average temperature per day based on the data provided below. Want to group all dates by each day of the week and find the average temperature for each. What function would be best suited for this task? Date <fctr> AvgTemp ...

Implementing dynamic classes for each level of ul li using JavaScript

Can anyone help me achieve the goal of assigning different classes to each ul li element in vanilla Javascript? I have attempted a solution using jQuery, but I need it done without using any libraries. Any assistance would be greatly appreciated! con ...

Utilize anychart.js to define the axis using JSON data

I'm relatively new to using anychart js and encountering some obstacles. I have a json file that is being fetched from an API, containing data on NBA players' statistics. You can find the json file here: My goal is to display the date data on th ...

Is there a way to modify the window's location without having to reload it and without resorting to any sne

Initially, I believed that the hash hack was a necessity, but after observing the recent updates from Facebook, my perspective has shifted. The original hash hack (not certain if this is the correct term) involved changing location.hash to save a state in ...

The concealment of the container is ineffective when attempting to hide it until all cached images are

My website has a background and a main container. I wanted to hide the container until the entire page had loaded, so I included #cover{opacity:0} at the beginning of the page and $(window).load(function() { $('#cover').css('opacity&apo ...

Exploring the incorporation of interfaces into Vue.js/Typescript for variables. Tips?

I have an interface:   export interface TaskInterface{ name: string description1: string time: string } and a component import { TaskInterface } from '@/types/task.interface' data () { return { tasks: [ { name: 'Create ...

Is the username you want available?

I am facing a challenge in my registration form validation process where I need to verify the username input using javascript and flask in python, but the implementation is unclear to me. The requirement is to utilize $.get in the javascript segment along ...

Is it possible to configure a unique Bearer Access Token in the "angular-oauth2-oidc" library?

For my Facebook login, I have set up a custom endpoint where the client sends the Facebook access token. In my Ionic App, I use the '@ionic-native/facebook/ngx' package to retrieve this token. Within a Laravel Json API controller, I utilize Soci ...

Connect the CSS active state to a JavaScript event

.el:active{ background:red; } Is there a way to associate the above CSS active state with a JavaScript event, like this: $('.el').on('active', function(){ img.show(); }); I want the image to remain visible when el is presse ...

What is the proper usage of a jwt token?

I'm completely new to this and I've dedicated all my time to figuring out how to create a mechanism for generating JWT tokens. These tokens are necessary for identifying the 'signed in' status of users. I opted for FastAPI, and after s ...

Aggregating and organizing all TypeScript files within the project while preserving the file hierarchy

Looking to utilize a task runner such as Grunt or Gulp to compile TS to JS files in various locations within the project folder. The goal is to ensure that the outputted JS files are placed in the same directory where the project will look for them alongsi ...

Modify object rotation animation direction using keyboard controls in Three.js

Adjusting the object rotation direction with key controls is within my capability by utilizing the following code: case 37: scene.rotation.x -= 0.01; break case 38: scene.rotation.z -= 0.01 break Nevertheless, the rotation remai ...

How to Retrieve Properties from Child Elements in NativeScript ngFor Directive

Working with a dynamically generated checklist in Angular/Nativescript: <StackLayout *ngIf="assessment"> <StackLayout *ngFor="let instance_item of assessment.exam_instance_items; let i= index"> <ns-examitem [attr.id] ...

Can you explain the significance of network activity groupings within the Firebug Net tab?

Can you explain the significance of different splitter lines on the Net tab in Firebug? In this screenshot, line 1 and 2 appear to be grouped together. However, line 3 stands alone. What do these groupings represent? ...

The requested URL /api/users/register does not exist. Error 404

While creating a money manager application utilizing the MERN Stack, I encountered an issue with posting data to the database. Whenever I click on the register button, an error is thrown stating that it Cannot POST /api/users/register. Despite setting up a ...

Iterate through a loop to remove DOM elements

I'm working on creating a loop that will be responsible for deleting DOM elements (one or more lines within an HTML table): <tr class="entireLine><input type="checkbox"></tr> <tr class="entireLine><input type="checkbox" che ...

Controller is not being triggered by Ajax method when there is a decimal value

I am currently working on implementing a time registration feature in my web application. Users can select the project they worked on and enter the number of hours spent on that project. Everything is functioning properly until users start adding half-hou ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...