import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { HelloComponent } from './hello.component';
import { DayAgoPipe } from './day-ago-pipe';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, HelloComponent, DayAgoPipe ],
bootstrap: [ AppComponent ]
})
export class AppModule { }
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
dataArray = [
{
name: 'Hum Chaar',
date: '02/15/2019'
},
{
name: 'Spider-man: far from home',
date: '07/05/2019'
},
{
name: 'Avengers: Endgame',
date: '24 April 2019'
}, {
name: 'Shazam',
date: 1562265000000
}
];
}
<h3>DayAgo Pipe - Example</h3>
<ul class="list-group">
<li *ngFor="let i of dataArray;" class="list-group-item d-flex justify-content-between align-items-center">
{{i.name}}
<span class="badge badge-primary badge-pill">
{{i.date | DayAgo}}
</span>
</li>
</ul>
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'DayAgo',
})
export class DayAgoPipe implements PipeTransform {
transform(value: any) {
if (value) {
const oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
const today = new Date();
const firstDate = new Date(today.getFullYear(), today.getMonth() + 1, today.getDate());
const nextDate = new Date(value);
const secondDate = new Date(nextDate.getFullYear(), nextDate.getMonth() + 1, nextDate.getDate());
const diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));
if (diffDays === 0) {
return 'Today';
} else {
return diffDays + ' days to go';
}
}
return value;
}
}