Greg-A
Greg-A

Reputation: 862

Compare and change the date format like today, yesterday,

I have the following data:

     {
       "content": [
       {
         "id": 15076772,
         "date": "2019-06-26T15:37:36"
       },
       {
        "id": 15074042,
        "date": "2019-03-05T15:06:57"
       },
       {
        "id": 15073812,
        "date": "2019-09-17T14:32:18"
       },
       {
        "id": 15073810,
        "date": "2019-09-18T14:31:56"
       }
     ]
   }

and I would like to convert each date to a specific format depending on the date of the day

if the newDate() = 2019-09-18T14: 31: 56 we would post today if the newDate() is not equal to the date of the day but to that of yesterday would be displayed yesterday

then after the days of the week depending on the date and after a week of departure the normal date of the data. a bit like the dates displayed in a chat system

I do not know if angular can do it automatically

I do not know if angular can do it automatically, I know that Moment.js can do it with calendar time.

If anyone could teach me that would be nice.

Upvotes: 3

Views: 4324

Answers (2)

Muhammad Shahab
Muhammad Shahab

Reputation: 411

Pipe for Today, Yesterday, and Date

import { DatePipe } from '@angular/common';
import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'niceDateFormat'
})
export class NiceDateFormatPipe implements PipeTransform {
  transform(value) {

    const today = new Date()
    const yesterday = new Date(today)
    yesterday.setDate(yesterday.getDate() - 1)

       if (value.getFullYear() == today.getFullYear() && value.getMonth() == today.getMonth() && value.getDate() == today.getDate())
       return "Today";
     else if (value.getFullYear() == yesterday.getFullYear() && value.getMonth() == yesterday.getMonth() && value.getDate() == yesterday.getDate())
       return "Yesterday";
    else{
      return (new DatePipe("en-US")).transform(value, 'dd/MM/yyyy');
    }
 }
}

In HTML file

<div>{{createdAt | niceDateFormat}} </div> 

Upvotes: 2

Andrei Tătar
Andrei Tătar

Reputation: 8295

Angular doesn't have this built in but you can just build your own pipe or use an existing one (https://github.com/AndrewPoyntz/time-ago-pipe)

Not developed by me, but a good example:

https://github.com/AndrewPoyntz/time-ago-pipe/blob/master/time-ago.pipe.ts

If you don't mind it not updating as time passes, you can just make it pure and keep it simple for your case only (today, yesterday, etc.).

@Pipe({
    name:'timeAgo',
    pure:false
})
export class TimeAgoPipe implements PipeTransform, OnDestroy {
    private timer: number;
    constructor(private changeDetectorRef: ChangeDetectorRef, private ngZone: NgZone) {}
    transform(value:string) {
        this.removeTimer();
        let d = new Date(value);
        let now = new Date();
        let seconds = Math.round(Math.abs((now.getTime() - d.getTime())/1000));
        let timeToUpdate = (Number.isNaN(seconds)) ? 1000 : this.getSecondsUntilUpdate(seconds) *1000;
        this.timer = this.ngZone.runOutsideAngular(() => {
            if (typeof window !== 'undefined') {
                return window.setTimeout(() => {
                    this.ngZone.run(() => this.changeDetectorRef.markForCheck());
                }, timeToUpdate);
            }
            return null;
        });
        let minutes = Math.round(Math.abs(seconds / 60));
        let hours = Math.round(Math.abs(minutes / 60));
        let days = Math.round(Math.abs(hours / 24));
        let months = Math.round(Math.abs(days/30.416));
        let years = Math.round(Math.abs(days/365));
        if (Number.isNaN(seconds)){
            return '';
        } else if (seconds <= 45) {
            return 'a few seconds ago';
        } else if (seconds <= 90) {
            return 'a minute ago';
        } else if (minutes <= 45) {
            return minutes + ' minutes ago';
        } else if (minutes <= 90) {
            return 'an hour ago';
        } else if (hours <= 22) {
            return hours + ' hours ago';
        } else if (hours <= 36) {
            return 'a day ago';
        } else if (days <= 25) {
            return days + ' days ago';
        } else if (days <= 45) {
            return 'a month ago';
        } else if (days <= 345) {
            return months + ' months ago';
        } else if (days <= 545) {
            return 'a year ago';
        } else { // (days > 545)
            return years + ' years ago';
        }
    }
    ngOnDestroy(): void {
        this.removeTimer();
    }
    private removeTimer() {
        if (this.timer) {
            window.clearTimeout(this.timer);
            this.timer = null;
        }
    }
    private getSecondsUntilUpdate(seconds:number) {
        let min = 60;
        let hr = min * 60;
        let day = hr * 24;
        if (seconds < min) { // less than 1 min, update every 2 secs
            return 2;
        } else if (seconds < hr) { // less than an hour, update every 30 secs
            return 30;
        } else if (seconds < day) { // less then a day, update every 5 mins
            return 300;
        } else { // update every hour
            return 3600;
        }
    }
}

Upvotes: 4

Related Questions