Search code examples
angulardatedata-conversionng-bootstrapngb-datepicker

Angular Bootstrap - ngbDatepicker - Convert selected Date into Date Object


in form, for date field using angular bootstrap - ngbDatepicker

<input  ngbDatepicker #d="ngbDatepicker" [readonly]="true"
                            [minDate]="{year: 1900, month: 1, day: 1}"
                            [formControl]="empForm.controls['dob']" />

and the date is. enter image description here

Here trying to create a Date Object, to replace the employee form date. But getting a DIFFERENT Date

let oDob = new Date(employeeToSave.dob['year'], employeeToSave.dob['month'],  employeeToSave.dob['day']);

Thu Jan 02 2020 00:00:00 GMT+0530 (India Standard Time) the selected date "2019-12-02" is now "2020-01-02"


Solution

  • In Date() indexing of month is 0 based you whatever number you want to enter like december(12th month) will have value 11. So try putting (month-1) in new Date().

    Like shown below:

    let oDob = new Date(employeeToSave.dob['year'], employeeToSave.dob['month']-1,  employeeToSave.dob['day']);
    

    Working snippet :

    let month=12;
    let year = 2019;
    let day = 12;
    dob = new Date(year,month,day);
    console.log("wrong Date : "+dob);
    
    dob2 = new Date(year,month-1,day);
    console.log("correct Date : "+dob2);