You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

PrimeNG <p-calendar>报错:date.getMonth is not a function 技术求助

Fixing "TypeError: date.getMonth is not a function" with PrimeNG p-calendar

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:

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:17:36