要在Angular中格式化输入的日期和时间,可以使用Angular的DatePipe。以下是使用或不使用Angular Material的两种解决方法的示例代码:
在模板中使用matDatepicker指令来选择日期,并使用MatInput指令来显示和输入日期。
HTML模板:
  
   
在组件中导入DatePipe并使用它来格式化选定的日期。
TypeScript代码:
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'app-date-format-example',
  templateUrl: './date-format-example.component.html',
  styleUrls: ['./date-format-example.component.css']
})
export class DateFormatExampleComponent {
  selectedDate: Date;
  constructor(private datePipe: DatePipe) {}
  formatDate(): string {
    return this.datePipe.transform(this.selectedDate, 'yyyy-MM-dd');
  }
}
在模板中使用原生的input元素来选择日期,并使用Angular的ngModel指令来绑定选定的日期。
HTML模板:
在组件中导入DatePipe并使用它来格式化选定的日期。
TypeScript代码:
import { Component } from '@angular/core';
import { DatePipe } from '@angular/common';
@Component({
  selector: 'app-date-format-example',
  templateUrl: './date-format-example.component.html',
  styleUrls: ['./date-format-example.component.css']
})
export class DateFormatExampleComponent {
  selectedDate: Date;
  constructor(private datePipe: DatePipe) {}
  formatDate(): string {
    return this.datePipe.transform(this.selectedDate, 'yyyy-MM-dd');
  }
}
这两种解决方法都使用了Angular的DatePipe来格式化日期。在formatDate方法中,this.datePipe.transform函数接受两个参数:要格式化的日期和格式字符串。在示例代码中,使用了yyyy-MM-dd格式来格式化日期,你可以根据需要修改格式字符串。