dateangularcalendarprimengonselect

Changing the Date Format the p-Calendar Transfers


I have a component, p-Calendar.

I had no trouble finding a way to receive the date I selected, and modify it.

<p-calendar 
                [showIcon]="true"
                (onSelect)="onSelectMethod($event)"
                [(ngModel)]="myDate"
                [dataType]="date"
                >
</p-calendar>

So basically when I hit a different date in the calendar, it does catch the date correctly. It will transfer this information: "Thu Dec 08 2016 00:00:00 GMT-0500 (Eastern Standard Time)"

While I can see that all this detail is useful, I really just want my component to receive: 12/08/16.

Is there any simple way to do this, perhaps some inherent method that comes with the calendar, without manually doing string modifications in my code? I read the documentation and couldn't find the information I am looking for.

The onBlur method seems to be transferring the data in the way I want it to. Unfortunately onBlur only works when you type in the date manually, or when you're one date selection behind. It would be great to somehow call PrimeNG's onBlur method after you made a selection in the calendar drop-down.


Solution

  • I wouldn't particularly recommend this as it's a hacky solution, it is probably better to do transformations of the myDate as appropriate for display or other purposes.

    If you really, really want to do this so that the myDate in your component only contains a short date without all that time and location information you can go ahead and separate out the model bindings to make it work like so:

    template.html

    <p-calendar [ngModel]="myDate"
                (onSelect)="onSelectMethod($event)"
                [dataType]="date">
    </p-calendar>
    

    component.ts

    onSelectMethod(event) {
      let d = new Date(Date.parse(event));
      this.myDate = `${d.getMonth()+1}/${d.getDate()}/${d.getFullYear()}`;
    }
    

    Here's a functioning demo: http://plnkr.co/edit/IGRfXjtqIo0TEr2iDC06?p=preview

    In case you were wondering about applying a pipe, you would do a straight [(ngModel)]="myDate" bind and, where you want to see the short date in the template do {{myDate | date: 'MM/dd/yy'}}