Home > OS >  Date field in angular reducing month by 1 when user keying in year field in angular
Date field in angular reducing month by 1 when user keying in year field in angular

Time:05-12

I have a date field defined in HTML

<input type="date" name=""  (change)="handleBlur($event)" min="1970-01-01" max="9999-12-31"
       value="{{ somedate| date:'yyyy-MM-dd' }}">

and in ts file i am handling onchange event

    handleBlur(event: any) {
   this.somedate= new Date(event.target.value).toISOString()
    console.log('after', this.somedate)
    this.formobject.controls['somedate'].setValue(this.somedate)
    this.appService.updateSaveDataValue({ somedate: this.somedate})
  }

This date control works great in some X countries, but not in others. I mean that the user can choose a date from the calendar control and also type in a date value. However, when a user uses the identical tool from the US region, this control behaves strangely. When the year is changed, each key in reduces the day by one, and when the user changes the day, the month is reduced by one. I don't know how to fix it or what's causing the problem.

CodePudding user response:

JavaScript Date objects have a time component. new Date(...) will create a new Date object with the time of 'now' in the user's current time zone. When converting that date object to an ISO string, it will standardize the time component, which can result in the date itself changing.

For example, consider if I select the date April 2, 2022 at exactly 12:30am in the morning in the time zone GMT 1. When .toISOString() is called on this date object, it will be converted to April 1, 2022 at 11:30pm for GMT 0. This can happen in reverse as well for times close to midnight.

To avoid this, you can manually create the ISO string from the day, month, and year on the date object, or you can enlist a library to help do it for you. Several libraries are out there that can help with managing dates, such as momentjs, Day.js, date-fns, etc.

  • Related