Reputation: 409
I implement a pipe which gets two value and finds the duration between them,it counts the duration in days if duration is less than 1 day it returns 0, but i don't want to show 0 in that case, i want to display "recently" if duration is less than a day.
HTML
<div>{{firstdate | myPipe : agent.lastUpdated}} d ago</div>
pipe.ts
import { PipeTransform, Pipe } from "@angular/core";
@Pipe({
name: 'myPipe',
pure: true
})
export class durationPipe implements PipeTransform{
transform(firstDate:any , secondDate:any):any{
if(!firstDate || !secondDate){
return firstDate;
}
const dropdt:any = new Date(firstDate);
const pickdt:any = new Date(secondDate);
const time = +((firstDate - secondDate) / (24 * 3600 * 1000));
// console.log("this is currentTime "+firstDate);
// console.log("this is userTime "+secondDate);
const a = time.toString().split('.',1);
// console.log("time is "+a);
return a;
}
}
Upvotes: 0
Views: 40
Reputation: 2646
There are a few ways of cause in implementing such task.
First one is quick but quite bad for performance because of relatively a lot of bindings:
<div>
<span *ngIf="firstdate | myPipe : agent.lastUpdated">
{{firstdate | myPipe : agent.lastUpdated}} d ago
</span>
<span *ngIf="!(firstdate | myPipe : agent.lastUpdated)">
recently
</span>
</div>
I'd suggest you create two pipes: one for calculating the difference in days and the second one to display correctly.
@Pipe({
name: 'dayDiff',
pure: true
})
export class DayDiff implements PipeTransform {
private millisecondsInDay = 24 * 3600 * 1000;
transform(from: any , till: any): any {
if(!from || !till){
return from;
}
const fromDate = new Date(from);
const tillDate = new Date(till);
return Math.floor((firstDate - secondDate) / this.millisecondsInDay);
}
}
...
@Pipe({
name: 'dayDiffDisplay',
pure: true
})
export class DayDiffDisplay implements PipeTransform {
transform(diff: number): any {
if(!diff){
return 'recently';
}
return `${diff} d ago`;
}
}
So the usage is simply:
{{firstdate | dayDiff : agent.lastUpdated | dayDiffDisplay}}
Upvotes: 1