Your Privacy Matters: We use our own and third-party cookies to improve your experience on our website. By continuing to use the website we understand that you accept their use. Cookie Policy
30
DatepickerComponet: Invalid date when converting input value to Date object
posted

I have an Angular template which implements an IgxDatePickerComponent. I am having an issue trying to format the date to a UK format for both the drop-down part of the control and the input part.

Here is my code for the control

 <igx-date-picker  #dateFromDatePicker mode="dropdown" locale="en-GB"
             cancelButtonLabel="close" todayButtonLabel="today">
              <ng-template igxDatePickerTemplate let-openDialog="openDialog" let-value="value"
                  let-displayData="displayData">
                  <igx-input-group type="border">
                      <igx-prefix (click)="openDialog(dropDownTarget)">
                          <igx-icon>today</igx-icon>
                      </igx-prefix>
                      <label igxLabel for="dropDownTarget">Start Date</label>
                    <input #dropDownTarget  class="igx-date-picker__input-date" igxInput [value]="displayData"
                          [igxMask]="'00/00/0000'" [placeholder]="'dd/mm/yyyy'"  (blur)="changeStartDate($event)"/>
                  </igx-input-group>
              </ng-template>
          </igx-date-picker>


And the component code is

changeStartDate(event{
    const dateValue = this.dateFromDatePicker.displayData; //Value passed from template is, for example: "24/04/2020"
    if (dateValue !== ' '{
      const parsedDate = new Date(dateValue);
      if (this.isDateValid(parsedDate)) {
        this.startDate = parsedDate;
      }
    } else {
      this.dateFromDatePicker.deselectDate();
      this.startDate = dateValue;
    }
  }
The result of parsedDate is "invalid date".

I need to convert "29/04/2020" into a valid date.

Parents
No Data
Reply
  • 1300
    Offline posted

    Hello Jason,

    After investigating this further, I determined that parsedDate is invalid, because when a mask is used the returned value: dateValue is a string with no spaces for example: 24042020 and to create a new Date from this one the string should be subtracted and passed to new Date as: new Date(year, month, day). This could be achieved the following way:

    this.day = dateValue.toString().substr(0,2);

        this.month = dateValue.toString().substr(2,2);

        this.year = dateValue.toString().substr(4,4);

        this.date = new Date(

          parseInt(this.year),

          parseInt(this.month) - 1,

          parseInt(this.day)

        );

    Please let me know if you need additional information regarding this matter.

    Regards,

    Monika Kirkova,

    Infragistics

Children
No Data