首页 > 解决方案 > 如何在 Angular 和 TypeScript 中格式化日期?

问题描述

我有一个显示日期的表格。

我的表格同时显示日期和时间,但我只想显示日期。

这是我的代码:

import {DatePipe, formatDate} from '@angular/common';
import * as moment from 'moment/moment';

export class RegistrationModel{
    firstName: string;
    lastName: string;
    middleName: string;
    nickname: string;
    createdAt: string;
    applicantCV: string;
    mobileNumber: string;
    emailAddress: string;

    datePipe = new DatePipe('en-US');

  constructor(response){
    //formatDate(this.createdAt, 'M/d/yy', 'en-US');
    this.firstName = response.firstName;
    this.lastName = response.lastName;
    this.middleName = response.middleName;
    this.nickname = response.personalData.nickname;
    this.createdAt = response.createdAt;
    this.datePipe.transform(this.createdAt, 'M/d/yy');
    this.applicantCV = response.applicantCV;
    this.mobileNumber = response.contactInfo.mobileNumber;
    this.emailAddress = response.contactInfo.emailAddress;
  }

}

表格截图

标签: angulartypescript

解决方案


我猜您在转换日期后忘记重新分配createdAt变量。

this.createdAt = this.datePipe.transform(new Date(this.createdAt), 'M/d/yy');

编辑

您似乎还必须先将 createdAt 转换为 Date。


推荐阅读