我们从时间 Select 器获得的输出为02:30
,因此我们需要相应地分割它.我们可以在:
上使用字符串拆分,然后使用一元+
将拆分的字符串转换为数字,最后设置小时和分钟!
combineDateTime(date: Date, time: string): Date {
const combinedDateTime = new Date();
combinedDateTime.setFullYear(date.getFullYear());
combinedDateTime.setMonth(date.getMonth());
combinedDateTime.setDate(date.getDate());
const [hours, minutes] = time.includes(':') ? time.split(':') : [0, 0];
combinedDateTime.setHours(+hours);
combinedDateTime.setMinutes(+minutes);
return combinedDateTime;
}
完整代码:完整代码:
TS :
import { Component } from '@angular/core';
import { MatDatepickerModule } from '@angular/material/datepicker';
import { MatInputModule } from '@angular/material/input';
import { MatFormFieldModule } from '@angular/material/form-field';
import { provideNativeDateAdapter } from '@angular/material/core';
import { FormsModule } from '@angular/forms';
import { NgxMaterialTimepickerModule } from 'ngx-material-timepicker';
import { CommonModule } from '@angular/common';
/** @title Basic datepicker */
@Component({
selector: 'datepicker-overview-example',
templateUrl: 'datepicker-overview-example.html',
standalone: true,
providers: [provideNativeDateAdapter()],
imports: [
MatFormFieldModule,
MatInputModule,
MatDatepickerModule,
FormsModule,
NgxMaterialTimepickerModule,
CommonModule,
],
})
export class DatepickerOverviewExample {
OraPrenotazione: string = '00:00';
DataPrenotazione: Date = new Date();
combinedDateTime: any = null;
combineDateTime(date: Date, time: string): Date {
const combinedDateTime = new Date();
combinedDateTime.setFullYear(date.getFullYear());
combinedDateTime.setMonth(date.getMonth());
combinedDateTime.setDate(date.getDate());
const [hours, minutes] = time.includes(':') ? time.split(':') : [0, 0];
combinedDateTime.setHours(+hours);
combinedDateTime.setMinutes(+minutes);
return combinedDateTime;
}
}
HTML:
<mat-form-field>
<mat-label>Data Appuntamento</mat-label>
<input
matInput
[matDatepicker]="picker"
[(ngModel)]="this.DataPrenotazione"
/>
<mat-hint>DD/MM/YYYY</mat-hint>
<mat-datepicker-toggle matIconSuffix [for]="picker"></mat-datepicker-toggle>
<mat-datepicker #picker></mat-datepicker>
</mat-form-field>
<label>Ora Appuntamento</label>
<ngx-timepicker-field
[format]="24"
[(ngModel)]="this.OraPrenotazione"
[minutesGap]="15"
></ngx-timepicker-field>
<button
(click)="combinedDateTime = combineDateTime(DataPrenotazione, OraPrenotazione)"
>
combine
</button>
Final DATE: {{combinedDateTime | date : 'full'}}
Stackblitz Demo