【问题标题】:how to format date in Component of angular 5如何在角度5的组件中格式化日期
【发布时间】:2018-06-19 09:39:21
【问题描述】:

我是 Angular 新手,希望在组件 ngOnInit 方法中格式化日期。我见过一些使用管道运算符格式化数据的例子,但我不知道如何在组件文件中格式化日期。

下面是代码

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

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


}

【问题讨论】:

  • Typescript 是一套超级 javascript,该解决方案也可以工作
  • 你的意思是我可以使用相同的 js 逻辑并在这里使用它。这是一种标准的做法吗,或者打字稿会有一些内置的东西来处理这个
  • 是的,您可以使用相同的逻辑来实现这一点。
  • Java 脚本的问题它过于开放和松散。它的限制性这就是我使用打字稿的原因。我不想使用 javascript。

标签: angular angular-cli


【解决方案1】:

您可以找到more information about the date pipe here等格式。

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

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

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

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

【讨论】:

  • 谢谢朋友,你能建议我在哪里可以找到打字稿教程吗?
  • 嗯,全网,不过我猜official website应该是最多的,你也应该看看Angular website b> 因为您的大部分问题都会在那里得到解答(包括这个!)
  • 是的,但我在文档中找不到任何日期/地图/设置相关主题
  • 试试.transform(yourDate, 'yyyyMMddhhmmss')或类似的东西
  • 如果您使用en-US 以外的任何其他语言环境,请不要忘记按照here 的说明注册语言环境。
【解决方案2】:

同样有formatDate

const format = 'dd/MM/yyyy';
const myDate = '2019-06-29';
const locale = 'en-US';
const formattedDate = formatDate(myDate, format, locale);

根据 API,它将日期字符串、日期对象或时间戳作为参数。

问题:开箱即用,仅支持 en-US

如果您需要添加其他语言环境,您需要添加它并在您的 app.module 中注册它,例如西班牙语:

import { registerLocaleData } from '@angular/common';
import localeES from "@angular/common/locales/es";
registerLocaleData(localeES, "es");

不要忘记添加相应的导入:

import { formatDate } from "@angular/common";

【讨论】:

  • 谢谢,这对我有用,首先它给出了一个错误,在将本地添加到它工作的模块之后!
【解决方案3】:

请参考以下链接,

https://angular.io/api/common/DatePipe

**Code Sample**

@Component({
 selector: 'date-pipe',
 template: `<div>
   <p>Today is {{today | date}}</p>
   <p>Or if you prefer, {{today | date:'fullDate'}}</p>
   <p>The time is {{today | date:'h:mm a z'}}</p>
 </div>`
})
// Get the current date and time as a date-time value.
export class DatePipeComponent {
  today: number = Date.now();
}

{{今天 |日期:'MM/dd/yyyy'}} 输出:2019 年 9 月 17 日

{{今天 |日期:'shortDate'}} 输出:17/9/19

【讨论】:

    【解决方案4】:

    另一个选项可以使用内置的角度formatDate 函数。我假设您正在使用反应形式。这里todoDate是模板中的日期输入字段。

    import {formatDate} from '@angular/common';
    
    this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多