在 angular 中将复杂时间戳转换为正常时间

Converting a complex timestamp to normal time in angular

我有一个像

这样的时间戳

2021-03-12T14:55:35.454Z

我想在ts文件中像这样(如下)将其转换为正常时间

2:55pm

我在 angular 工作。知道的请帮忙看看。我尝试搜索其他 Whosebug 问题,但找不到确切的解决方案

知道的请帮忙

使用,Angular的内置DatePipe。

如果你想在html

中使用它
{{ yourDate| date: 'shortTime'}}

或在组件文件中:

const myDate = new DatePipe('en-US').transform(rawDate,'shortTime' );

rawDate 是您的复杂时间戳。

要了解有关可用格式的更多信息,请前往 https://angular.io/api/common/DatePipe

Moment js 是一个不错的时区选择。您可以在 angular 中使用 datepipe,prashant vats 正确提到了这一点。

如果您只想将 iso 转换为 am/pm 格式,您也可以使用以下方法。

import { Component, OnInit, VERSION } from "@angular/core";

@Component({
  selector: "my-app",
  templateUrl: "./app.component.html",
  styleUrls: ["./app.component.css"]
})
export class AppComponent implements OnInit {
  name = "Angular " + VERSION.major;
  convertedtime = null;
  public convertTime(date: string): string {
    if( !date ) {
      return null;
    }
    const dateTimeArr = date.split("T");
    const timeArr = dateTimeArr[1].split(":");
    const hour = +timeArr[0] > 12 ? +timeArr[0] % 12 : (timeArr[0] === "00") ? 12 : timeArr[0];
    const min = timeArr[1];
    const ampm = +timeArr[0] > 12 ? "pm": "am";
    return `${hour}:${min}${ampm}`;
  }
  ngOnInit() {
    this.convertedtime = this.convertTime("2021-03-12T14:55:35.454Z");
  }
}

https://stackblitz.com/edit/angular-ivy-y6aic1?file=src%2Fapp%2Fapp.component.ts