I am looping a data response from API and displaying in Angular. In this data, i have few fields with date format. Is it possible to check the object and format if its date to 'd-MMM-yyyy' format?
<table >
<tbody>
<tr *ngFor="let item of rowSource | keyvalue: keepOrder" >
<th >
{{item.key}}
</th>
<td >
{{item.value | date:'MMM'}}
</td>
</tr>
</tbody>
</table>
Payload
{
"Employee ID": 1506,
"First Name": "Sean",
"Last Name": "Less",
"Phone": "9234567896",
"Email": "[email protected]",
"Hired Date": "2021-06-07T00:00:00", <-- Wanted to format this
}
CodePudding user response:
Use the date pipe as needed :
{{item.value | date:'d-MMM-yyyy'}}
All notations can be found here
CodePudding user response:
You can create a moment pipe.
first, you need to install the moment library then create a pipe.
momentpipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import * as moment from 'moment';
@Pipe({ name: 'dateFormat' })
export class MomentPipe implements PipeTransform {
transform(value: Date | moment.Moment, dateFormat: string): any {
return moment(value).format(dateFormat);
}
}
You must include your pipe in the declarations array of the AppModule.
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { MomentPipe } from './momentPipe';
@NgModule({
imports: [
// Your Modules
],
declarations: [
AppComponent,
...........,
MomentPipe
],
providers: []
})
export class AppModule { }
Use it in your View/Html like below.,
{{ item.value | dateFormat: ''d-MMM-yyyy''}}
If you want to check that given data is date or not then you can craete one function in TS file.
TS
isValidDate(val): boolean { return moment(val).isValid(); } // true
And you can use in your HTML
HTML
<td *ngIf=isValidDate(item.value)>
{{item.value | dateFormat: ''d-MMM-yyyy''}}
</td>