Reputation: 41
i use the DatePicker from Angular Material and I would like to change the output format to yyyy/mm/dd
.
Currently it prints the date in the following format: Wed Nov 14 2018 00:00:00 GMT+0100 (Central European Normal Time)
How can I do this?
datepicker = new FormControl('', [Validators.required]);
console.log(this.datepicker.value.toString());
Upvotes: 4
Views: 29547
Reputation: 1
First,
import {formatDate} from '@angular/common';
Then,
let val = this.dynamicForm.get('datePicker').value;
val = formatDate(val,'yyyy/MM/dd','en');
this.dynamicForm.controls['datePicker'].setValue(val);
Upvotes: 0
Reputation: 3931
You can use Moment.js to format your date to "YYYY/MM/DD" format
moment(this.datepicker.value).format('YYYY/MM/DD')
using moment will help us change date into different formats
Upvotes: 2
Reputation: 4838
DatePicker
works with date object. When you print on debugging console you will always see the date in full mode.
If you want that your component shows the date in a specific format, you need to configure the library on the module.
@NgModule({
providers: [
{provide: MAT_DATE_LOCALE, useValue: 'en-GB'},
],
})
export class MyApp {}
More information are available on official documentation. I hope it helps.
Upvotes: 9
Reputation: 4174
To format only the output of a variable, you should use pipes.
The Data Pipe can be found on the docs.
Basically, on your component.html
, you have to do:
<p>The date is {{ datepicker.value | date:'yyyy/MM/dd' }}</p>
This will display the datapicker.value
formatted as yyyy/mm/dd
. You have a lot of other options to format your output based on pipes and even create your owns.
To format the date on the .ts
file, you have a couple of options.
import { DatePipe } from '@angular/common';
new DatePipe('en').transform(this.datepicker.value, 'yyyy/MM/dd');
Date
object, adding a format
method)Upvotes: 3