PrimeNG <p-calendar>报错:date.getMonth is not a function 技术求助
Hey there, let's get this sorted out quickly! The error you're seeing happens because PrimeNG's <p-calendar> component expects a proper JavaScript Date object, but your backend is sending a numeric timestamp (like 1524665731000) instead. Numbers don't have a getMonth() method—hence the error.
Here are a few straightforward solutions:
1. Convert the timestamp to a Date object in your component (Recommended)
When you fetch the data from your backend, transform the timestamp field into a Date before binding it to your model. Here's how that might look with Angular's HttpClient:
this.http.get('/api/your-application-endpoint').subscribe((response: any) => { // Turn the numeric timestamp into a Date instance response.entryDate = new Date(response.entryDate); this.applicationData = response; // Assign to your component's model });
Now you can bind directly to <p-calendar> without issues:
<p-calendar [(ngModel)]="applicationData.entryDate"></p-calendar>
2. Use a custom pipe for template-side conversion
If you prefer not to modify the raw backend data in your component, create a simple pipe to handle the conversion on the fly:
First, generate the pipe:
import { Pipe, PipeTransform } from '@angular/core'; @Pipe({ name: 'timestampToDate' }) export class TimestampToDatePipe implements PipeTransform { transform(timestamp: number): Date | null { return timestamp ? new Date(timestamp) : null; } }
Don't forget to declare this pipe in your Angular module!
Then use it in your template, and handle the reverse conversion when the user selects a date:
<p-calendar [ngModel]="applicationData.entryDate | timestampToDate" (ngModelChange)="applicationData.entryDate = $event.getTime()" ></p-calendar>
The (ngModelChange) event converts the selected Date back to a timestamp so your model stays consistent with the backend's format.
3. Adjust backend output (Optional)
If you have control over the backend, you can configure it to return dates in ISO 8601 string format (e.g., "2018-04-25T12:15:31.000Z"). Angular automatically parses these strings into Date objects, so you won't need any frontend conversion at all.
Quick recap
The core issue is mismatched data types: <p-calendar> needs a Date object, but you're passing a number. Any of these methods will bridge that gap and get your calendar input displaying correctly.
内容的提问来源于stack exchange,提问作者Rob DePietro

