Friday, October 13, 2017

How to show a date is today or yesterday or last week etc using pipe - Angular

Let us check how we can convert a timestamp/date to today or last week etc using a simple angular pipe. This will be very help full for users to understand the time very clearly. We can achieve this by using a simple pipe.

Let us create a simple pipe and a method for converting date into more user readable format.

Pipe


@Pipe({
    name: 'niceDateFormatPipe',
})
export class niceDateFormatPipe implements PipeTransform {
    transform(value: string) {
       
       var _value = Number(value);
       
       var dif = Math.floor( ( (Date.now() - _value) / 1000 ) / 86400 );
       
       if ( dif < 30 ){
            return convertToNiceDate(value);
       }else{
           var datePipe = new DatePipe("en-US");
           value = datePipe.transform(value, 'MMM-dd-yyyy');
           return value;
       }
    }
}

function convertToNiceDate(time: string) {
    var date = new Date(time),
        diff = (((new Date()).getTime() - date.getTime()) / 1000),
        daydiff = Math.floor(diff / 86400);

    if (isNaN(daydiff) || daydiff < 0 || daydiff >= 31)
        return '';

    return daydiff == 0 && (
        diff < 60 && "Just now" ||
        diff < 120 && "1 minute ago" ||
        diff < 3600 && Math.floor(diff / 60) + " minutes ago" ||
        diff < 7200 && "1 hour ago" ||
        diff < 86400 && Math.floor(diff / 3600) + " hours ago") ||
        daydiff == 1 && "Yesterday" ||
        daydiff < 7 && daydiff + " days ago" ||
        daydiff < 31 && Math.ceil(daydiff / 7) + " week(s) ago";
}

Html


<p>{{currentTime | niceDateFormatPipe }}</p>

We are done. I will share module code as well. Here I will be importing our new pipe.

Module


import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { DatePipe } from '@angular/common';
import {niceDateFormatPipe} from './pipes'

@NgModule({
  declarations: [
    AppComponent,niceDateFormatPipe
  ],
  imports: [
    BrowserModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

You can update the pipe for getting any other date format. For more example of date formatting in angular refere this post. In this article we have discussed about converting a date into a more readable format by using a simple angular pipe.

Related Info

1. Share data between components using a service file.

2. Disable submit button until all mandatory fields are filled - Angular

3. Angular client side pagination.

4. Angular show more/less pagination

No comments :

Post a Comment