在组件中设置日期格式并在HTML中应用它
在组件中,在ngOnInit函数中使用以下代码设置日期格式:
import { formatDate } from '@angular/common';
export class MyComponent implements OnInit {
// set the date format
dateFormat: string = 'yyyy-MM-dd';
ngOnInit() {
// format your date to display it in the desired format
const today = new Date();
const formattedDate = formatDate(today, this.dateFormat, 'en-US');
// use the formatted date
console.log(formattedDate); // prints '2021-11-22'
}
}
在HTML模板中使用Angular日期管道将日期格式化为短格式:
{{ myDate | date:'shortDate' }}
其中myDate是一个Date对象。这将以短格式(MM/dd/yyyy)显示日期。您也可以传递您自己的日期格式到管道中,就像这样:
{{ myDate | date:'yyyy/MM/dd' }}
这将以格式'yyyy/MM/dd'显示日期(例如2021/11/22)。
上一篇:Angular日历点击事件