如何使用Angular中的自定义管道将秒转换并显示为年,月,日?

Ash*_*eal 3 html typescript angular

我通过API调用获得秒(有效性),并且需要在frontEnd中以年,月,日为单位显示它……如何使用自定义管道或其他方式显示它?

我已经创建了一个自定义管道,但是如何返回值?

 export class SecondsToDaysPipe implements PipeTransform {
    transform(val: number): number {
       let totalSeconds = val;
      }
  }
Run Code Online (Sandbox Code Playgroud)

预期:有效期:01年03个月03天

小智 5

您可以使用矩和矩持续时间格式库。通过以下命令安装两个库

npm install moment --save
npm install moment-duration-format --save
Run Code Online (Sandbox Code Playgroud)

还添加类型以在角度中使用它

npm i @types/moment-duration-format --save
Run Code Online (Sandbox Code Playgroud)

安装完成后,创建如下所示的管道,

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
import 'moment-duration-format';

@Pipe({
  name: 'secondToYearMonthDays'
})
export class SecondToYearMonthDaysPipe implements PipeTransform {

  transform(value: any, args?: any): any {
    return moment.duration(value, 'seconds').format('Y [years]: M [months]: D [days]');
  }

}
Run Code Online (Sandbox Code Playgroud)

并在html中使用此管道

<label>{{72650000| secondToYearMonthDays}}</label>
 Output : 2 years: 3 months: 19 days
Run Code Online (Sandbox Code Playgroud)

您还可以通过传递带有管道名称的参数来使该管道对于不同的时间单位和显示格式更加通用。

您可以在此处签出受支持的格式:https : //github.com/jsmreese/moment-duration-format