如何为PrimeNG p-calendar设置默认日期和时间
showTime Enabled) Hey there! Let's walk through how to properly set the default date and time for your p-calendar component. First, let's recap your current setup to align on context:
Your template code:
<p-calendar formControlName="pre_check_in" [defaultDate]="defaultDate" [minDate]="dateTime" showTime="true" hourFormat="24" showButtonBar="true" required>Your TS code snippet:
private passService(qsUserId) { this._appService.getEditVisitData(qsUserId).subscribe((data) => { console.log(data); this.editCheckinData = data; this.editCheckinF... // Your form initialization logic here }); }
Step 1: Ensure Your Data is a Valid Date Object
PrimeNG's p-calendar relies on native JavaScript Date objects to render dates and times correctly. If your database returns a string (e.g., ISO 8601 format like 2024-05-20T16:45:00) or timestamp, you'll need to convert it first.
Step 2: Update the Form Control Directly
Since you're using reactive forms with formControlName, the most reliable way to set the default value is to update the form control itself (you can still use [defaultDate] as a fallback, but form control values take priority).
Modify your TS code like this:
private passService(qsUserId) { this._appService.getEditVisitData(qsUserId).subscribe((data) => { console.log(data); this.editCheckinData = data; // Convert database value to Date object (adjust if your data is a timestamp) const preCheckinDateTime = new Date(data.pre_check_in); // Update the form control with the converted date/time this.editCheckinF.get('pre_check_in')?.setValue(preCheckinDateTime); // Optional: Sync with [defaultDate] if you want it to reflect the same value this.defaultDate = preCheckinDateTime; }); }
Step 3: Set a Fallback Default (If Needed)
If you want a default date/time to show before fetching data from the database (e.g., current date and time), initialize defaultDate in your component's ngOnInit or constructor:
ngOnInit() { // Set current date/time as initial default this.defaultDate = new Date(); }
Step 4: Handle Edge Cases
- If your database returns a numeric timestamp, use
new Date(timestamp)to convert it. - If time values are off, double-check timezone handling: p-calendar uses the browser's local timezone by default, so ensure your database data is adjusted to match or convert it explicitly.
内容的提问来源于stack exchange,提问作者Atul Stha

