How can we customize the date from moment js? I want to display only Ex: Thu 10 of the month. How can we achieve that using moment or pipe need your help.
app.component.html
<h2>{{ dateCtr.value | date }}</h2>
app.component.ts
import { Component } from '@angular/core';
import {FormControl} from '@angular/forms';
import {MomentDateAdapter, MAT_MOMENT_DATE_ADAPTER_OPTIONS} from '@angular/material-moment-adapter';
import {DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE} from '@angular/material/core';
import _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment} from 'moment';
const moment = _rollupMoment || _moment;
// See the Moment.js docs for the meaning of these formats:
// https://momentjs.com/docs/#/displaying/format/
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'LL',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ],
providers: [
// `MomentDateAdapter` can be automatically provided by importing `MomentDateModule` in your
// application's root module. We provide it at the component level here, due to limitations of
// our example generation script.
{
provide: DateAdapter,
useClass: MomentDateAdapter,
deps: [MAT_DATE_LOCALE, MAT_MOMENT_DATE_ADAPTER_OPTIONS]
},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
})
export class AppComponent {
dateCtr = new FormControl(moment());
incrementDate(){
this.dateCtr.setValue(moment(this.dateCtr.value).add(1, 'days').format());
}
decrementDate(){
this.dateCtr.setValue(moment(this.dateCtr.value).subtract(1, 'days').format());
}
}
pipe.ts
import { Pipe, PipeTransform } from '@angular/core';
import { DatePipe } from '@angular/common';
@Pipe({ name: 'mypipe' })
export class Mypipe implements PipeTransform {
// adding a default value in case you don't want to pass the format then 'yyyy-MM-dd' will be used
transform(date: Date | string, day: number, format: string = 'yyyy-MM-dd'): string {
date = new Date(date); // if orginal type was a string
date.setDate(date.getDate() - day);
return new DatePipe('en-US').transform(date, format);
}
}
How can we customize the date from moment js? I want to display only Ex: Thu 10 of the month. How can we achieve that using moment or pipe need your help.
step 1 : import { Datepipe } from "@angular/comman"; // import inside app.modules.ts
step 2: use
<h2>{{ dateCtr.value | date: "EE d" }}</h2>
instead of <h2>{{ dateCtr.value | date }}</h2>