How to change Mat-Datepicker date format to DD/MM/YYYY in simplest way?
The easiest way is to change the locale:
Add the following to the providers section of your module:
{ provide: MAT_DATE_LOCALE, useValue: 'en-GB' }
How to format material datepicker date value to "MM-DD-YYY" format in Angular 6?
You can use DatePipe to format the date as per your requirement.
Import in main.module.ts
import { DatePipe } from '@angular/common';
and add Datapipe
in Providers array.
Then in related component import the same as
import { DatePipe } from '@angular/common';
and in constructor
constructor(private datePipe : DatePipe)
{
}
and to use date pipe just use
this.datePipe.transform(your_date, 'MM-dd-yyyy');
Have a look at StackBlitz Example where I have consoled the date value in MM-dd-yyyy
format.
angular material 2, change datepicker Date Format "MM/DD/YYYY" to "DD/MM/YYYY" strange behavior
1/ DOCS: By cusomising the parse and display format with a custom date atapter
In the custom Date Adapter (yours is AppDateAdapter), add a parse method to parse the new date format (DD/MM/YYY) to a date valid date:
for example for the DD/MM/YYYY format, parse could be:
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
working stackblitz: https://stackblitz.com/edit/angular-material-datepicker-format?embed=1&file=app/date.adapter.ts
your complete date adapter:
export class AppDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
format(date: Date, displayFormat: any): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
The advantage of this approach is you could also custom the format of monthYearLabel
in the display constants and could have a calendar which looks like:
converting angular date picker date to 'YYYY-MM-DD' format
const momentDate = new Date(event.value); // Replace event.value with your date value
const formattedDate = moment(momentDate).format("YYYY/MM/DD");
console.log(formattedDate);
Angular reactive Form material Date picker manual input format DD/MM/YYYY
Here another version of an AppDateAdapter:
export class AppDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
format(date: Date, displayFormat: string): string {
if (displayFormat == "input") {
let day = date.getDate();
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(day) + '/' + this._to2digit(month) + '/' + year;
} else if (displayFormat == "inputMonth") {
let month = date.getMonth() + 1;
let year = date.getFullYear();
return this._to2digit(month) + '/' + year;
} else {
return date.toDateString();
}
}
private _to2digit(n: number) {
return ('00' + n).slice(-2);
}
}
export const APP_DATE_FORMATS =
{
parse: {
dateInput: {month: 'short', year: 'numeric', day: 'numeric'}
},
display: {
dateInput: 'input',
monthYearLabel: 'inputMonth',
dateA11yLabel: {year: 'numeric', month: 'long', day: 'numeric'},
monthYearA11yLabel: {year: 'numeric', month: 'long'},
}
}
Angular Material Datepicker input format
You need to build a custom date adapter like this:
export class CustomDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
const year = Number(str[2]);
const month = Number(str[1]) - 1;
const date = Number(str[0]);
return new Date(year, month, date);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
format(date: Date, displayFormat: Object): string {
date = new Date(Date.UTC(
date.getFullYear(), date.getMonth(), date.getDate(), date.getHours(),
date.getMinutes(), date.getSeconds(), date.getMilliseconds()));
displayFormat = Object.assign({}, displayFormat, { timeZone: 'utc' });
const dtf = new Intl.DateTimeFormat(this.locale, displayFormat);
return dtf.format(date).replace(/[\u200e\u200f]/g, '');
}
}
and then use it in your app:
@NgModule({
....
providers: [
{ provide: DateAdapter, useClass: CustomDateAdapter }
]
})
DEMO
How to change angular material datepicker format
You need to provide an object containing the formats you wish to use. The object should look something like:
export const MY_FORMATS = {
parse: {
dateInput: 'LL',
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'YYYY',
},
};
You then need to add that in to your providers array, like so:
import { MAT_DATE_FORMATS } from '@angular/material/core';
import { MomentDateAdapter } from '@angular/material-moment-adapter';
//...
providers: [
{provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE]},
{provide: MAT_DATE_FORMATS, useValue: MY_FORMATS},
],
Here is a StackBlitz demo to show it working
Change formatting of date upon calling value
Luctia, imagine we received some like
{
name:'Name'
birthdate:'1980-10-21'
}
You can has a service like
getData()
{
return this.httpClient(...).pipe(map(x=>{
x.birthdate=new Date(x.birthdate)
return x
})
}
//See that subscribing to the service in birthdate we has an object Date
getList(){
return this.httpClient(...).pipe(map((list:any[])=>{
list.forEach(x=>{
x.birthdate=new Date(x.birthdate)
})
return list
})
}
//see that when subcribing to List, return an array of object with birthdate is Date
updateData(data)
{
//we calculate a birthdate string
const birthdate=data.getFullYear()+'-'+
('00'+(data.getMonth()+1).slice(-2)+'-'+
('00'+data.getDate()).slice(-2)
//send to post the data but the birthDate a string
return this.httpClient.post(...,{...data,birthdate:birthdate})
}
How to format data after select Datepicker Material?
why not try to make another loop for the datepicker count
let datePickerCount = 50;
for (const key of Object.keys(formGroup)) {
for(let i = 1; i <= datePickerCount ; i++){
if (key == 'date'+i) {
somedate+i = formatDate(new Date(event), "MM/dd/yyyy", "en-US")
}
}
don't forget to import formatDate
import { formatDate } from '@angular/common';
Related Topics
How to Allow Chrome to Access My Camera on Localhost
Setting Iframe Height to Scrollheight in Reactjs
Innerhtml Inserts Only [Object Htmldivelement]
Edit Table Row Inline on Click of Edit in Angular
Onchange Is Not Triggering in React Js
How to Make Mongoose Not Insert Empty Array or Object Fields into a Document
Display a Loading Icon While Images Loads
Update Url With Value from Input on Click With React
How to Check If Value Is in Array With Angularjs
Php - Return Confirm Within PHP Issue
Converting Json Object to CSV Format in JavaScript
How to Make Any Hovered Color Darker/Lighter That the Original
Remove Specific Characters from String Jquery
Removing Currency Symbol and Replacing Comma With Point Using Pure JavaScript
Invalid Attempt to Spread Non-Iterable Instance
If Check Box Checked Disable Other, If Unchecked Enable All in React