Search code examples
angularpipe

Angular2 How to transform year to age using pipe


I want to create a pipe where it can transform year (1992) to age (26) (Korean Age)

I figure I should load current year (2017), subtract 1992 and add +1

but I am not sure how to make this happen with pipe.

I appreciate your help in advance.


Solution

  • Blockquote

    Here is my example using moment.js (it also shows months along with years, feel free to remove it):

    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;
        }
    
    }
    

    And then just use this pipe: {{person.birthday|age}} in your HTML, where person.birthday is Javascript Date object.