How to use Date-FNS in VueJS? - javascript

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')
},

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

date-fns: how to define a default locale app-wide?

It's pretty straightforward to set a locale in a per-function call basis:
import { formatRelative, subDays } from 'date-fns'
import { ptBR } from 'date-fns/locale'
formatRelative(subDays(new Date(), 3), new Date(), { locale: ptBR })
But how do I set a default locale to be used app-wide?
As I know, there is no such option. Usually I create custom wrapper function around formatDate functions and pass there application locale. You could store locale in global variables or in app level stores:
formatRelativeWrap.js
import { formatRelative } from 'date-fns'
import AppStore from 'appStore'
export default (date1, date2, locale) => {
return formatRelative(date1, date2, { locale: locale || AppStore.defaultLocale})
}
As #Pointy mentioned there is note about this in official docs - https://date-fns.org/v2.22.1/docs/I18n - second example.
This has been released in version 2.29: https://date-fns.org/v2.29.0/docs/setDefaultOptions
// Set global locale:
var setDefaultOptions = require('date-fns/setDefaultOptions')
import { es } from 'date-fns/locale'
setDefaultOptions({ locale: es })

Is it possible to format the date inside an object?

Is something like this possible? Trying to format the date formatted_short
<Generic type="startDate" jsonldtype="DateTime" schema={{
startDate: `${props.dates[0].start_date.formatted_short.format('YYYY-MM-DD')}`,
endDate: `${props.dates[0].end_date.formatted_short}`,
doorTime: `${props.dates[0].start_date.time}`,
}}/>
You can use react-moment for to formart date.
https://www.npmjs.com/package/react-moment#formatting
You can use like this;
import React from 'react';
import Moment from 'react-moment';
export default class MyComponent extends React.Component {
render() {
return (
// format : your format.
<Moment format="YYYY/MM/DD">
1976-04-19T12:59-0500 // your date string
</Moment>
);
}
}
Moment Example:
<Generic type="startDate" jsonldtype="Date" schema={{
startDate: Moment(`${props.dates[0].start_date.formatted_short}`).format('YYYY-MM-DD'),
endDate: Moment(`${props.dates[0].end_date.formatted_short}`).format('YYYY-MM-DD'),
doorTime: Moment(`${props.dates[0].start_date.time}`).format('hh:mm:ss')
}}/>
Should anybody need it

Angular Material DatePicker: Month and Day, Exclude Year

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

How to get date and time in mm-dd-yyy hh-mm-ss in typescript?

Currently, I am getting date time in the following format 'mm/dd/yyyy, hh:mm:ss'.
How to get it in the following format 'mm-dd-yyyy hh-mm-ss'.
How to achieve this without using any library, and preferably by passing some args to the function itself?
Below is the code that am currently using (in Angular 5)
console.log(new Date().toLocaleString(undefined, { hour12: false }));
make use of DatePipe , that is provided by angular framework
{{ strDate | date :'MM-dd-yyyy hh-mm-ss' }
or in code you can do like this
import { DatePipe } from '#angular/common';
#Component({
selector: 'test-component',
templateUrl: './test-component.component.html'
})
class TestComponent {
constructor(private datePipe: DatePipe) {}
formatDate(date= new Date()) {
return this.datePipe.transform(date,'MM-dd-yyyy hh-mm-ss' );
}
}
check here : DatePipe

Categories