I am receiving from the API a datetime like this: 2021-03-21T22:00:00
Here is my component.ts
ELEMENT_DATA: ReservationList[];
displayedColumns: string[] = ['fullName', 'brand', 'model', 'rentalStartDate', 'rentalEndDate', 'pickUpLocation', 'dropOffLocation', 'totalPrice', 'createdOn'];
dataSource = new MatTableDataSource<ReservationList>(this.ELEMENT_DATA);
//here the data is taken from the API call
public getAll() {
let resp = this.service.reservationList();
resp.subscribe(report => this.dataSource.data= report as ReservationList[])
}
In the HTML the date is displayed like this:
<ng-container matColumnDef="rentalEndDate">
<th mat-header-cell *matHeaderCellDef mat-sort-header> RentalEndDate </th>
<td mat-cell *matCellDef="let element"> {{element.rentalEndDate}} </td>
</ng-container>
And in the table the date is displayed like this 2021-03-21T22:00:00
I want to have the date displayed without the T character and just the date.
Here are a couple ways to accomplish this:
You could use String.replace()
:
removeT(input: string) {
return input.replace('T', ' ');
}
<td mat-cell *matCellDef="let element"> {{ removeT(element.rentalEndDate) }}</td>
You could also use the DatePipe
to format the date:
<td mat-cell *matCellDef="let element"> {{ element.rentalEndDate | date:'yyyy-MM-dd H:mm:ss' }}</td>
The date pipe is nice because it let's you easily get the date in more readable formats.
Here is what the output would look like with these different methods:
Date String "2021-03-21T22:00:00"
Date with string.replace('T', ' ') "2021-03-21 22:00:00"
Date w/Pipe ('yyyy-MM-dd H:mm:ss') "2021-03-21 22:00:00"
Date w/Pipe ('yyyy-MM-dd') "2021-03-21"
Date w/Pipe ('fullDate') "Sunday, March 21, 2021"
Date w/Pipe "Mar 21, 2021"