[FIXED] PrimeNG <p-calendar> error date.getMonth is not a function

Issue

I am getting the error

core.es5.js:1020 ERROR Error: Uncaught (in promise): TypeError: date.getMonth is not a function

TypeError: date.getMonth is not a function

I get this error whenever I try to use 2 way data binding when I recevie my JSON object from my backend. My backend data type is a Date but it will not show backup in the p-calendar input. Please help!

{ "applicationId": 1, "entryDate": 1524665731000, "ongoingDescription": "<p>Ongoing entry should end in (5081421)</p>", "activeFlag": "Y" }

HTML

<div class="form-group">
  <label>Date of the Ongoing Incident</label>
  <br>
  <p-calendar required [(ngModel)]="entry.entryDate" name="entryDate" #entryDate="ngModel" [showIcon]="true" [showTime]="true" dateFormat="mm/dd/y 'EST'" hourFormat="24"></p-calendar>
  <div class="alert alert-danger" *ngIf="entryDate.touched && !entryDate.valid" >The date and time of the incident are required</div>
</div>

TS

 entryDate: Date;

 entry = {
 }

constructor(private service: OngoingService, private route: ActivatedRoute, 
private router: Router, private location: Location) {

this.id = this.route.snapshot.paramMap.get('id');
if (this.id) this.service.get(this.id).take(1).subscribe(service => 
this.entry = service);

}

ngOnInit() {

}

ngAfterContentInit() {

}

ngAfterViewInit() {

}

Any information will help

I tried to also assign the
entryDate = new Date(); and entryDate = new Date(this.entryDate);

Solution

It can’t convert to Date from JSON automatically, you have to assign it yourself.

this.id = this.route.snapshot.paramMap.get('id');
if (this.id) {
    this.service.get(this.id).take(1)
        .subscribe(service => this.entry = { entryDate: new Date(service.entryDate) });
}

Your variable entryDate is never assigned or used. You can remove it unless you want to have a reference to p-calendar component and have access to its’ properties and methods. In that case you have to decorate it with an attribute like:

@ViewChild('entryDate')
entryDate: Calendar;

Note that the type is Calendar, not Date. It’s a primeng type and should be imported from primeng

Answered By – Dainius LukÅ¡a

Answer Checked By – Clifford M. (Easybugfix Volunteer)

Leave a Reply

(*) Required, Your email will not be published