I am searching a lot on google. But I have the material datetime picker. So not the date picker, but the datetime picker. And I want to format the date-time , like in this format:
2021-02-15 23:59:59
But I try to do it without moment.js. Because it is not good practice. But if it can't be done without moment.js then be it.
So I have this js file:
const CUSTOM_DATE_FORMATS: NgxMatDateFormats = {
parse: {
dateInput: ''
},
display: {
dateInput: 'YYYY-MM-DD HH:mm:ss',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
}
};
#Component({
selector: 'app-widget-editor',
templateUrl: './widget-editor.component.html',
styleUrls: ['./widget-editor.component.css'],
providers: [
{provide: DateAdapter, useClass: AppDateAdapter},
{provide: MAT_DATE_FORMATS, useValue: APP_DATE_FORMATS}
]
})
export class WidgetEditorComponent implements OnInit, AfterContentInit {
#ViewChild('picker') picker;
start: string;
end: string;
interval: string;
duration: string;
yrange: number[];
constructor(private editorService: EditorService ) {}
reOpenCalender() {
let self = this;
setTimeout(() => {
self.picker.open();
} );
}
}
and this is template:
<div class="form-group row">
<label for="start" class="editor-label col-sm-4"><strong> Time start:</strong></label>
<input [(ngModel)]="start" format [ngModelOptions]="{standalone: true}" type="text" class="date" id="start" value="start" matInput [ngxMatDatetimePicker]="picker">
<ngx-mat-datetime-picker #picker></ngx-mat-datetime-picker>
<span class="ml-2" (click)= "reOpenCalender()">
<fa-icon [icon]="faCalendarAlt" size="1x" #picker [styles]="{'color': '#B7B7B7'}"
></fa-icon>
</span>
</div>
But the format is still like this:
2/16/2021, 04:36:32
and not in this format:
2021-02-15 23:59:59
So what I have to change?
Thank you
here is an answer to your question.
How to change angular material datepicker format
We have to use -
import { MAT_DATE_FORMATS } from '#angular/material';
and pass the defined format to provider along with above
Related
I'm using currently moment.js in my project. I want to remove "T" and +02:00. There must be a date and time only. But if I use the .format() method of moment.js I get the default datetime.
I want to format this datetime:
from ' 2022-02-11T04:20:13+02:00 ' to ' 2022-02-11 04:20:13 '
back
import * as moment from 'moment';
date_times: any;
constructor() {
this.date_times = moment().format('YYYY-MM-DD HH:mm:ss');
}
front
<ion-item>
<ion-label>Select date & time</ion-label>
<ion-datetime displayFormat="D MMM YYYY H:mm A" (ionChange)="showdate()" [(ngModel)]="date_times"></ion-datetime>
</ion-item>
{{date_times }}
moment().format('YYYY-MM-DD HH:mm:ss') will give you the format you want but since you are using date_times as the ngModel of <ion-datetime> component, its value has been changed after you initialized the value in the constructor().
You can format date_times when you print it out by using Pipe like this:
my-datetime-format.pipe.ts:
import { Pipe, PipeTransform } from '#angular/core';
import * as moment from 'moment';
#Pipe({
name: 'myDateTimeFormat'
})
export class myDateTimeFormatPipe implements PipeTransform {
transform(value: string): string {
return moment(value).format('YYYY-MM-DD HH:mm:ss');
}
}
In template:
{{ date_times | myDateTimeFormat }}
How do I create a Month and Day Date Picker in Angular, excluding hide year?
This following link will do a Month and Year picker. I am trying to manipulate it, to do Month and Day. Replacing YYYY with DD is not working.
Stackblitz:
https://stackblitz.com/angular/gxymgjpprdy?file=src%2Fapp%2Fdatepicker-views-selection-example.ts
Real code from Stackblitz:
Typescript:
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 {MatDatepicker} from '#angular/material/datepicker';
// Depending on whether rollup is used, moment needs to be imported differently.
// Since Moment.js doesn't have a default export, we normally need to import using the `* as`
// syntax. However, rollup creates a synthetic default module and we thus need to import it using
// the `default as` syntax.
import * as _moment from 'moment';
// tslint:disable-next-line:no-duplicate-imports
import {default as _rollupMoment, Moment} 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: 'MM/YYYY',
},
display: {
dateInput: 'MM/YYYY',
monthYearLabel: 'MMM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MMMM YYYY',
},
};
/** #title Datepicker emulating a Year and month picker */
#Component({
selector: 'datepicker-views-selection-example',
templateUrl: 'datepicker-views-selection-example.html',
styleUrls: ['datepicker-views-selection-example.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 DatepickerViewsSelectionExample {
date = new FormControl(moment());
chosenYearHandler(normalizedYear: Moment) {
const ctrlValue = this.date.value;
ctrlValue.year(normalizedYear.year());
this.date.setValue(ctrlValue);
}
chosenMonthHandler(normalizedMonth: Moment, datepicker: MatDatepicker<Moment>) {
const ctrlValue = this.date.value;
ctrlValue.month(normalizedMonth.month());
this.date.setValue(ctrlValue);
datepicker.close();
}
}
HTML:
<mat-form-field>
<input matInput [matDatepicker]="dp" placeholder="Month and Year" [formControl]="date">
<mat-datepicker-toggle matSuffix [for]="dp"></mat-datepicker-toggle>
<mat-datepicker #dp
startView="multi-year"
(yearSelected)="chosenYearHandler($event)"
(monthSelected)="chosenMonthHandler($event, dp)"
panelClass="example-month-picker">
</mat-datepicker>
</mat-form-field>
I do not want year option below in green, would like to disable year
Other Resources:
https://material.angular.io/components/datepicker/overview#watching-the-views-for-changes-on-selected-years-and-months
Angular Material Date picker disable the year selection
I hope you are expecting date format like DD/MMM. If so then change dateInput in display and parse object like below
dateInput: 'DD/MMM'
Hope this helps.
Here is the stackblitz code.
https://stackblitz.com/edit/angular-hw54xf
So , first in the html file
<mat-form-field class="mat-50-left" (click)="updateCalendarUI()">
<input matInput [matDatepicker]="picker_start"
placeholder="Date de début" required formControlName="dt_start" (click)="picker_start.open();">
<mat-datepicker-toggle matSuffix (click)="picker_end.open(); updateCalendarUI()"></mat-datepicker-toggle>
<mat-datepicker #picker_start startView="year"></mat-datepicker>
</mat-form-field>
in the .ts file
import {DateAdapter, NativeDateAdapter} from "#angular/material/core";
import * as moment from "moment";
export class AppDateAdapter extends NativeDateAdapter {
format(date: Date, displayFormat: Object): string {
// use what format you need
return moment(date).format('DD MMM');
}
}
add in providers
providers: [{provide: DateAdapter, useClass: AppDateAdapter}]
To update calendar UI
updateCalendarUI(): void {
setTimeout(() => {
let calendar = document.getElementsByClassName('mat-
calendar').item(0);
if (calendar) {
calendar['style'].height = '275px';
calendar['style']['padding-top'] = '15px';
}
let header = document.getElementsByClassName('mat-calendar-
header').item(0);
if (header) {
header['style'].display = 'none';
}
let yearLabel = document.getElementsByClassName('mat-calendar-body-
label').item(0);
if (yearLabel) {
yearLabel['style'].display = 'none';
}
}, 1);
}
I am using Angular8 and want to format date and time but I have to use date pipe with same format pattern again and again as shown below
<p>{{ myDate | date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ myOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate date: 'dd MMM yyyy, h:mm a' }}</p>
and same format date: 'dd MMM yyyy, h:mm a' is to be used in each and every component of my project.
Is there a way where I can provide a global config in the providers of my App Module, something like this
#NgModule({
providers: [
{provide: LOCAL_PIPE_DATE_PATTERN, useValue: 'ddMMyy'},
],
})
export class AppModule {}
and just use the date pipe as
<p>{{ myDate | date }}</p>
<p>{{ myOtherDate | date }}</p>
<p>{{ otherVar }}</p>
<p>{{ myOtherOtherDate | date:'MMyyDD' }}</p> (If format changed)
You could create a local DatePipe in your ts file and convert the date in the Format you use the most and the rest of the time use the Pipeline it self.
yourNormalDateString : Date = new Date();
datePipe = new DatePipe('YOUR_LOCAL_CODE');
dateToDisplay = this.datePipe.transform(this.yourNormalDateString, 'Your Date Format String');
You could create a new date pipe in your project and initialize always the format
#Pipe({
name: "myDate"
})
export class MyDatePipe {
constructor(private datePipe: DatePipe) {}
transform(value: any): string {
let format = "dd MMM yyyy, h:mm a";
return this.datePipe.transform(new Date(value), format);
}
}
I have the form for date filter and I trying set the default value for the start and end date for date inputs.
<form [formGroup]="filter" (ngSubmit)="applyFilter()">
<mat-form-field>
<input matInput [matDatepicker]="start" formControlName="start" placeholder="Начальная дата">
<mat-datepicker-toggle matSuffix [for]="start"></mat-datepicker-toggle>
<mat-datepicker #start></mat-datepicker>
</mat-form-field>
<mat-form-field>
<input matInput [matDatepicker]="end" formControlName="end" placeholder="Конечная дата">
<mat-datepicker-toggle matSuffix [for]="end"></mat-datepicker-toggle>
<mat-datepicker #end></mat-datepicker>
</mat-form-field>
And TS part
refreshFilter() {
const now = new Date();
const monthAgo = new Date().setMonth(now.getMonth() - 1).toString();
console.log(monthAgo)
console.log(now)
this.filter = new FormGroup({
start: new FormControl(monthAgo, []),
end: new FormControl(now, [])
});
}
My console.log() for the month ago is 1533908066234 but for new Date is Mon Sep 10 2018 16:34:26 GMT+0300 and with timestamp form input doesn't work. How to get correct format date of month ago for success setting into FormControl?
If you Want to format a date in Angular you can use the DatePipe
Try to use the pipe to format.
This allows you to format a date value according to locale rules.
If you need more info about this you also can check here:
https://angular.io/api/common/DatePipe
Also do this monthAgo.toLocaleDateString()
I hope this helps!
I followed the following steps and it worked as expected:
created a new Angular 6 app using CLI and added Angular Materials to project
imported FormsModule and ReactiveFormsModule in app.module.ts
copied exactly the same html markup as you provided into app.component.html
added the below code in app.component.ts
import { Component, OnInit } from '#angular/core';
import {FormControl, FormGroup} from '#angular/forms';
#Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
filter: FormGroup
ngOnInit() {
let now = new Date();
let monthAgo = new Date();
monthAgo.setMonth(now.getMonth() - 1);
this.filter = new FormGroup({
start: new FormControl(monthAgo, []),
end: new FormControl(now, [])
});
}
}
Hope this helps.
I found the solution:
const now = new Date();
const monthAgo = new Date(now.getFullYear(), now.getMonth() - 1, now.getDate(), now.getHours());
this.filter = new FormGroup({
start: new FormControl(monthAgo , []),
end: new FormControl(now, [])
});
I converting the date from timestamp to string format. That's all.
If somebody knows how to rewriting this more elegantly, I would be grateful.
How to Change language of Datepicker of Material Angular?
I can't find in documentation for Angular material 2.
Here is a plunkr https://plnkr.co/edit/unzlijtsHf3CPW4oL7bl?p=preview
<md-input-container>
<input mdInput [mdDatepicker]="picker" placeholder="Choose a date">
<button mdSuffix [mdDatepickerToggle]="picker"></button>
</md-input-container>
<md-datepicker #picker></md-datepicker>
import {MAT_DATE_LOCALE} from '#angular/material';
&
providers: [{ provide: MAT_DATE_LOCALE, useValue: 'es-ES' }]
Do this in tpv.modules.ts
md-datepicker provides setLocale method which can be used to set any language (list of locale).
Here's an example of setting locale to 'fr':
export class DatepickerOverviewExample {
constructor(private dateAdapter: DateAdapter<Date>) {
this.dateAdapter.setLocale('fr');
}
}
One thing to keep in mind, md-datepicker's default date parsing format is mm/dd/yyyy, so if a locale has a different date format (for 'fr' its dd/mm/yyyy), we will need to define a class that extends NativeDateAdapter to parse the new date format. Without setting the proper date format, there will be an issue like this question.
import { NativeDateAdapter, DateAdapter, MD_DATE_FORMATS } from "#angular/material/core";
export class FrenchDateAdapter extends NativeDateAdapter {
parse(value: any): Date | null {
if ((typeof value === 'string') && (value.indexOf('/') > -1)) {
const str = value.split('/');
if (str.length < 2 || isNaN(+str[0]) || isNaN(+str[1]) || isNaN(+str[2])) {
return null;
}
return new Date(Number(str[2]), Number(str[1]) - 1, Number(str[0]), 12);
}
const timestamp = typeof value === 'number' ? value : Date.parse(value);
return isNaN(timestamp) ? null : new Date(timestamp);
}
}
#Component({
...
providers: [{provide: DateAdapter, useClass: FrenchDateAdapter}],
})
Plunker demo
Locale setting can be provided via MAT_DATE_LOCALE constant, but to change language dynamically you need to use DateAdapter as it is shown in https://material.angular.io/components/datepicker/overview#internationalization
#Component({
selector: 'app-root',
templateUrl: './app.component.html'
})
export class AppComponent {
constructor(private dateAdapter: DateAdapter<any>) {}
setFrench() {
// Set language of Datepicker
this.dateAdapter.setLocale('fr');
}
}
Here is another example when you need to configure locale from external script:
<script>
window.appConfig = {
language: 'fr',
// Other config options
// ...
};
<script>
<app-root></app-root>
In this case you should also use DateAdapter:
import {Injectable} from '#angular/core';
import {DateAdapter} from '#angular/material';
declare let window: any;
#Injectable()
export class AppConfigService {
appConfig = window.appConfig;
constructor(private dateAdapter: DateAdapter<any>) {
// Set language of Datepicker
this.dateAdapter.setLocale(this.appConfig.language);
}
}
For anyone who has a bug when editing input field (eg: putting DD/MM/YYYY will change it to MM/DD/YYYY or simply not working) create an adapter:
import { NativeDateAdapter } from '#angular/material';
export class FrenchDateProvider extends NativeDateAdapter {
parse(value: string) {
let it = value.split('/');
if (it.length == 3) {
return new Date(+it[2], +it[1] - 1, +it[0], 12);
}
}
format(date: Date, displayFormat: Object) {
return ('0' + date.getDate()).slice(-2) + '/' + ('0' + (date.getMonth() + 1)).slice(-2) + '/' + date.getFullYear();
}
}
Add it to your module as provider:
#NgModule({
providers: [
{ provide: DateAdapter, useClass: FrenchDateProvider }
]
})
export class SharedModule { }
For me the working solution is similar to vladernn's, however it should be:
import {MAT_DATE_LOCALE} from '#angular/material/core';
and
providers: [{ provide: MAT_DATE_LOCALE, useValue: 'pl' }]
in material.module.ts file.
Difference: new import address and shorter useValue code.
I tried this and worked for me
constructor(private _adapter: DateAdapter<any>, private translate:TranslateService ) {
this._adapter.setLocale(this.translate.getBrowserLang());
}