如何在角度 5 的组件中格式化日期 [英] how to format date in Component of angular 5

查看:28
本文介绍了如何在角度 5 的组件中格式化日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 angular 的新手,希望在组件 ngOnInit 方法中格式化日期.我看过一些示例,其中管道运算符用于格式化数据,但我不知道如何在组件文件中格式化日期.

I am new to angular and looking to format date in component ngOnInit method. I have seen some example where pipe operator are used to format the data but i dont know how to format date in component file.

下面是代码

export class DashboardComponent implements OnInit {
  formatdate = 'dd/MM/yyyy';
  constructor(private auth: AuthService) { }

  ngOnInit() {
    console.log(new Date().toISOString())
  }


}

推荐答案

您可以找到 更多信息关于这里的日期管道,例如格式.

You can find more information about the date pipe here, such as formats.

如果你想在你的组件中使用它,你可以简单地做

If you want to use it in your component, you can simply do

pipe = new DatePipe('en-US'); // Use your own locale

现在,您可以简单地使用它的转换方法,即

Now, you can simply use its transform method, which will be

const now = Date.now();
const myFormattedDate = this.pipe.transform(now, 'short');

这篇关于如何在角度 5 的组件中格式化日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆