Angular8: Global date format config - javascript

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);
}
}

Related

momentjs datetime format on frontend with angular

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 to format date with Angular material datetime picker

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

How can you retrieve multiple values with momentjs from firebase?

I get all data from firebase and store it on array and from that array i take all posted_at data (time when was something posted). My goal is to retrieve all that data in some sort of time format and problem is that it won't retrieve multiple values. I am using Vuejs.
<template>
<div v-for="data in array">
{{ time }}
</div>
</template>
<script>
import moment from 'moment'
export default{
data(){
return{
array:[]//example:1577200868199, 1577200868189,...
}
},
computed:{
time(){
moment(this.array.posted_at).format('MMMM Do YYYY, h:mm:ss a')
}
}
}
</script>
P.S. I have tried using a for and a while loop but it's not working
This is a nice case to use Vue filter
<template>
<div v-for="data in array">
{{ data | formatTime }}
</div>
</template>
<script>
import moment from 'moment'
export default{
data(){
return{
array: []//example:1577200868199, 1577200868189,...
}
},
filters: {
formatTime: function (value) {
return moment(value).format('MMMM Do YYYY, h:mm:ss a')
}
}
}
</script>
With moment you can only parse one item at a time, so you can change your code to loop over your array and parse each item individually. It would look something like this.
this.array.forReach(posted_at => {
moment(posted_at).format('MMMM Do YYYY, h:mm:ss a')
})

How to set date default value for reactive form in Angular 6?

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 use Date-FNS in VueJS?

I'm new to Date-FNS and I need to get this example to work in VueJS:
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
format(new Date(), '[Today is a] dddd')
//=> "Today is a Wednesday"
formatDistance(subDays(new Date(), 3), new Date())
//=> "3 days ago"
formatRelative(subDays(new Date(), 3), new Date())
//=> "last Friday at 7:26 p.m."
How to get it to work?
Just like moment js, all you need is to use the date library is to import and include it in your data:
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
export default {
data () {
return {
format,
}
}
}
And now in your template, you can use format as:
<template>
<p> Today's date is: {{ format(new Date(), 'dddd') }} </p>
</template>
With Locale:
I haven't tried the locale but it seems very straight forward. According to the manual I think this should work.
import { format, formatDistance, formatRelative, subDays } from 'date-fns'
import es from 'date-fns/locale/es'
window.locale = 'es'
export default {
data () {
return {
format,
}
},
methods: {
getFormat () {
return this.format(new Date(), 'dddd', {locale: window.locale})
}
}
}
And now in your template, you can use format as:
<template>
<p> Today's date is: {{ getFormat() }} </p>
</template>
I think if you spend a couple of minutes with it, you can get a better working solution for you.
Update with lazy loading approach
This option is good if you need to support many locales and want to pay attention to bundle sizes.
let dateFnsLocale
if (lang === 'en') { dateFnsLocale = await import('date-fns/locale/en-US') }
if (lang === 'hu') { dateFnsLocale = await import('date-fns/locale/hu') }
if (lang === 'fr') { dateFnsLocale = await import('date-fns/locale/fr') }
The reason why I'm not dynamically concatenating the lang to the import string is because I've found that in that case Webpack will not be able to decide which locales you'll import, and it takes all.
Personally I've started to store the dateFnsLocale in Vuex, so once your import is done you can commit it to state if you want, making it accessible throughout your application similarly as the global namespace of window did.
Original answer
If you need to support multiple locales I think it's best to do this in your main.js.
import { default as en } from 'date-fns/locale/en'
import { default as hu } from 'date-fns/locale/hu'
import { default as fr } from 'date-fns/locale/fr'
window.dateFnsLocales = {
hu,
fr,
en
}
Then anywhere in your script tags you can:
format(new Date(), 'dddd', {locale: window.dateFnsLocales[CURRENTLY SELECTED LOCALE]})
In the version v1.30.1 of date-fns you have to import/require from date-fns/something.
In order to make it work with Vuejs:
import format from "date-fns/format"
import distanceInWords from "date-fns/distance_in_words"
import subDays from "date-fns/sub_days"
export default {
name: "MyComponent",
computed: {
inWords () { return distanceInWords(subDays(new Date(), 3), new Date()) },
today () { return format(new Date(), '[Today is a] dddd') },
},
}
And the template tag:
<template>
<div>
<p>{{ inWords }}</p>
<p>{{ today }}</p>
</div>
</template>
Just got it to work:
In your template:
{{ formatDate() }}
Import:
import format from 'date-fns/format'
export default {
...
In your Method:
methods: {
formatDate: function () {
return format(new Date(), '[Today is a] dddd')
},

Categories