Angular 2 “time ago” pipe

前端 未结 8 1454
余生分开走
余生分开走 2020-12-08 04:56

I am trying to create a \'time ago\' pipe for my Angular 2 application.

It should transform a date to a string such as \'5 minutes ago\' or \'60 seconds ago\'. It wo

8条回答
  •  无人及你
    2020-12-08 05:17

    The accepted answer can not work with angular 7+.

    I followed this answer and customize for Vietnamese.

    https://stackoverflow.com/a/61341940/4964569

    I share for whom concern.

    import {Pipe, PipeTransform} from '@angular/core';
    
        @Pipe({
            name: 'dateAgo',
            pure: true
        })
        export class TimePipe implements PipeTransform {
        
            transform(value: any, args?: any): any {
                if (value) {
                    const seconds = Math.floor((+new Date() - +new Date(value)) / 1000);
                    if (seconds < 29) // less than 30 seconds ago will show as 'Just now'
                        return 'vừa mới đăng';
                    const intervals = {
                        'năm': 31536000,
                        'tháng': 2592000,
                        'tuần': 604800,
                        'ngày': 86400,
                        'giờ': 3600,
                        'phút': 60,
                        'giây': 1
                    };
                    let counter;
                    for (const i in intervals) {
                        counter = Math.floor(seconds / intervals[i]);
                        if (counter > 0){
                          return counter + ' ' + i + ' trước'; // singular (1 day ago)
                        }
                    }
                }
                return value;
            }
        }
    

提交回复
热议问题