0

I have the following HTML code for datepicker :

<mat-form-field class="input-form">
    <input matInput [matDatepicker]="picker" (click)="picker.open()" [formControl]="fieldIndividuEducation.control">
    <mat-datepicker-toggle matSuffix [for]="picker"></mat-datepicker-toggle>
    <mat-datepicker #picker></mat-datepicker>
    <mat-hint align="end">label</mat-hint>
</mat-form-field>

I need to get the date and then insert it in PGSQL database. I have the following code to retrieve it :

if(element.type == 'date' && element.control.value !== null) {
    let month = element.control.value.getUTCMonth() + 1;
    let day = element.control.value.getUTCDate() + 1;
    let year = element.control.value.getUTCFullYear();
    value = year + '-' + month + '-' + day;
}

The "+1" is because by default the selected date is one day before the selection, I don't know why.. But if I select the 01 May 2020 the result of value is : 2020-4-31

Do you have any idea to retrieve the correct selected date ?

Thanks

Nathan Cheval
  • 773
  • 2
  • 7
  • 32

1 Answers1

0

This is because you are getting UTC date and not the local date which depending on where you are could give value with one day difference. If you just do element.control.value.getMonth() you will get the month according to local time. Also, remember that the Months start from 0, so January will be '0' and December '11'

LalitaCode
  • 410
  • 4
  • 10