【问题标题】:Angular2 How to transform year to age using pipeAngular2如何使用管道将年份转换为年龄
【发布时间】:2017-04-06 16:30:07
【问题描述】:

我想创建一个管道,它可以将年份 (1992) 转换为年龄 (26)(韩国时代)

我想我应该加载当前年份(2017),减去 1992 并加上 +1

但我不确定如何使用管道实现这一点。

提前感谢您的帮助。

【问题讨论】:

  • 那么,您尝试过什么?具体问题是什么?
  • 由于并非所有人都在同一天出生,因此仅使用年份而不使用完整日期会得出错误的结果。

标签: angular pipe


【解决方案1】:

块引用

这是我使用 moment.js 的示例(它还显示月份和年份,请随意删除它):

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({
    name: 'age'
})
export class AgePipe implements PipeTransform {

    transform(value: Date): string {
        let today = moment();
                let birthdate = moment(value);
                let years = today.diff(birthdate, 'years');
                let html:string = years + " yr ";

                html += today.subtract(years, 'years').diff(birthdate, 'months') + " mo";

        return html;
    }

}

然后在你的 HTML 中使用这个管道:{{person.birthday|age}},其中person.birthday 是 Javascript Date 对象。

【讨论】:

  • 没有moment.js有解决办法吗?
【解决方案2】:

这里是 Luxon:

import { Pipe, PipeTransform } from "@angular/core";
import { DateTime } from "luxon";

/**
 * Tell the duration since a given time
 */
@Pipe({
  name: "timeSince",
})
export class TimeSincePipe implements PipeTransform {
  transform(
    value: string,
    precision: "years" | "months" | "days" = "years"
  ): string {
    let today = DateTime.now();
    let birthdate = DateTime.fromISO(value);

    let duration: any = today.diff(birthdate);
    let days, months, years: string;

    let html: string = "";
    switch (precision) {
      case "days":
        // Note: Going one unit lower give us integer/rounded values
        duration = duration.shiftTo("years", "months", "days", "hours");
        days = duration.days.toString();
        months = duration.months.toString();
        years = duration.years.toString();

        html += [years, "years", months, "months", days, "days"].join(" ");
        break;
      case "months":
        duration = duration.shiftTo("years", "months", "days");

        months = duration.months.toString();
        years = duration.years.toString();

        html += [years, "years", months, "months"].join(" ");
        break;
      default:
        // years
        duration = duration.shiftTo("years", "months");

        years = duration.years.toString();

        // Do not display unit when only years
        html += years;
        break;
    }

    return html;
  }
}

而你就是这样使用它的

{{ '2020-11-28T07:47:39.742Z' | timeSince:'days' }} --> 0 years 9 months 1 days

{{ '2020-11-28T07:47:39.742Z' | timeSince:'months' }} --> 0 years 9 months

{{ '2020-11-28T07:47:39.742Z' | timeSince }} --> 0 years

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-08-17
    • 2020-09-08
    • 2014-09-13
    • 1970-01-01
    相关资源
    最近更新 更多