【问题标题】:How to remove the T character from a date in Angular如何从Angular中的日期中删除T字符
【发布时间】:2021-03-25 21:59:10
【问题描述】:

我从 API 收到这样的日期时间:2021-03-21T22:00:00

这是我的组件.ts

 ELEMENT_DATA: ReservationList[];
 displayedColumns: string[] = ['fullName', 'brand', 'model', 'rentalStartDate', 'rentalEndDate', 'pickUpLocation', 'dropOffLocation', 'totalPrice', 'createdOn'];

  dataSource = new MatTableDataSource<ReservationList>(this.ELEMENT_DATA);

//here the data is taken from the API call
public getAll() {
  let resp = this.service.reservationList();
  resp.subscribe(report => this.dataSource.data= report as ReservationList[])
}

在 HTML 中,日期显示如下:

<ng-container matColumnDef="rentalEndDate">
    <th mat-header-cell *matHeaderCellDef mat-sort-header> RentalEndDate </th>
    <td mat-cell *matCellDef="let element"> {{element.rentalEndDate}} </td>
</ng-container>

并且在表格中日期显示如下 2021-03-21T22:00:00

我想让日期显示不带 T 字符,只显示日期。

【问题讨论】:

  • 这是 ISO 8601 日期。
  • 我建议你看看像Luxon这样的日期解析库
  • element.rentalEndDate.split("T")[0] 在 T 之前给出你的第一部分...

标签: angular typescript date datetime mat-table


【解决方案1】:

这里有几种方法可以做到这一点:

你可以使用String.replace():

removeT(input: string) {
  return input.replace('T', ' ');
}
<td mat-cell *matCellDef="let element"> {{ removeT(element.rentalEndDate) }}</td>

您也可以使用DatePipe 来格式化日期:

<td mat-cell *matCellDef="let element"> {{ element.rentalEndDate | date:'yyyy-MM-dd H:mm:ss' }}</td>

日期管道很不错,因为它让您可以轻松地以更易读的格式获取日期。

以下是使用这些不同方法的输出:

Date String                         "2021-03-21T22:00:00"
Date with string.replace('T', ' ')  "2021-03-21 22:00:00"
Date w/Pipe ('yyyy-MM-dd H:mm:ss')  "2021-03-21 22:00:00"
Date w/Pipe ('yyyy-MM-dd')          "2021-03-21"
Date w/Pipe ('fullDate')            "Sunday, March 21, 2021"
Date w/Pipe                         "Mar 21, 2021"

【讨论】:

  • 很好的答案!谢谢!哪种方法最合适?
  • 我可能会选择使用管道,因为它已经内置于 Angular 中。对现有代码的最小更改。
  • 谢谢!确实,变化很小。有效!再次感谢您!
猜你喜欢
  • 2021-09-11
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-10-25
  • 2014-11-16
  • 2017-05-05
  • 2018-11-03
相关资源
最近更新 更多