Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert string to type date in dynamically generated mat-table

I have a mat-table which displays columns Date, Before Time Period and After Time Period. Code for HTML :-

<ng-container
            matColumnDef="{{ column }}"
            *ngFor="let column of columnsToDisplay"
        >
            <th mat-header-cell *matHeaderCellDef>{{ column }}</th>
            <td mat-cell *matCellDef="let element">
                {{ element[column]  }}
            </td>
        </ng-container>

TypeScript Code:

columnsToDisplay = [
    'executionDate',
    'previousTimePeriod',
    'afterTimePeriod'
];
executionDate: string = new Date().toISOString().slice(0, 10);

If I use a pipe {{ element[column] | date: 'yyyy-MM-dd'}} to display Date of type string to date type then I am not able to see Before and After Time Period. How can I view date only as 'yyyy-MM-dd'

like image 232
Cpt Kitkat Avatar asked Feb 12 '19 07:02

Cpt Kitkat


Video Answer


2 Answers

create a pipe:

import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';

@Pipe({
  name: 'momentPipe',
  pure: false
})
export class MomentPipe implements PipeTransform {

  constructor() { }

  transform(value: string, dateFormat: string): any {
        return moment(value).format(dateFormat);
    }
}

then in html:

<span >{{ element[column] | momentPipe: 'dddd D MMM YYYY' }}</span>  

You need moment for this approach see here more formats

like image 130
Radu Tataru Avatar answered Oct 21 '22 20:10

Radu Tataru


My suggestion is to use angular momentjs

So it'll be simple that you can use its filter as

{{ element[column] | amParse: 'YYYY-MM-DDTHH:mm:ss.SSSSZ' | amDateFormat: 'yyyy-MM-dd' }}
like image 41
Nguyen Phong Thien Avatar answered Oct 21 '22 21:10

Nguyen Phong Thien