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
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 }}
I am having troubles creating a custom view with the typed big calendar, each time I use a calendar component such as Timegrid or any other in my custom Week component as in the example, I get a standard error such as react_devtools_backend.js:2560 Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
If I use standard HTML or non big calendar components, the custom week works though.
import {NavigateAction, TimeGrid} from 'react-big-calendar'
import moment = require('moment')
interface MyWeekProps {
date: Date
}
export class MyWeek extends React.Component<MyWeekProps> {
static title = (date: Date) => {
return `My awesome week: ${date.toLocaleDateString()}`
}
static navigate = (date: Date, action: NavigateAction) => {
switch (action) {
case 'PREV':
return moment(date).add(-3, 'day').toDate()
case 'NEXT':
return moment(date).add(3, 'day').toDate()
default:
return date
}
}
static range = (date: Date) => {
let start = date
let end = moment(start).add(2, 'day')
let current = start
let range = []
while (moment(current).isSameOrBefore(moment(end), 'day')) {
range.push(current)
current = moment(current).add(1, 'day').toDate()
}
return range
}
render() {
let {date} = this.props
let range = MyWeek.range(date)
return <TimeGrid range={range} eventOffset={15}/>
//return <div>{date}<div/> no error
}
}
then used as
import {MyWeek} from 'reparator/rendezVous/rendezVousCustomWeek'
...
return <Calendar
culture={culture}
localizer={localizer}
views={{month: true, week: MyWeek, day: true, agenda: true}}
style={{height: props.fullScreen ? '800px' : '500px', width: '100%'}}
messages={messages}
startAccessor="start"
endAccessor="end"
min={minimum}
max={maximum}
timeslots={timeslots}
step={step}
events={props.rendezVous.map((rdv: RendezVous) => toEvent(rdv))}
onSelectEvent={(event: EventRendezVous) => {
if (!props.readOnly) {
window.location.href = `#rendezVous/${event.id}/edition`
}
}}
dayPropGetter={customDayPropGetter}
slotPropGetter={customSlotPropGetter}
eventPropGetter={customEventPropGetter}
components={{
event: customEvent,
agenda: {
event: customEventAgenda,
},
}}
/>
so as Keith suggested, the typescript version has export issues and importing the untyped complete module solves the problem :
// #ts-ignore
import * as TimeGrid from 'react-big-calendar/lib/TimeGrid'
<TimeGrid {...this.props} range={range} eventOffset={15}/>
and use this
I am using date validation but it is not working for me because datepicker validation is lock my calendar after select less than date, so can you please suggest me how to fix this problem.
here is my code:
index.js
import React from 'react';
import moment from 'moment';
const processDate = date =>
date ? moment(date, date.length === 10 ? 'DD/MM/YYYY' :
null).format('MM/DD/YYYY') : null;
class Skills extends React.Component {
static propTypes = {
skills: PropTypes.array.isRequired,
};
onSubmitSkill(formData) {
const { paramValue } = this.props;
const skill = Object.assign({ employeeId: paramValue },
formData);
skill.startDate = processDate(skill.startDate);
skill.endDate = processDate(skill.endDate);
}
}
SkillsForm.js
import React, { Component } from 'react';
import { Input, DatePicker, Select } from 'components/Form';
import moment from 'moment';
import skillsValidations from './validations.js';
const selector = formValueSelector('academicYear');
const processDate = date => (date ? moment(date, date.length === 10 ? 'DD/MM/YYYY' : null) : null);
#connect(state => ({
startDate: selector(state, 'startDate'),
perm: state.auth.user.permissions,
}))
#reduxForm({
form: 'skills',
validate: skillsValidations,
})
export default class SkillsForm extends Component {
constructor(props) {
super(props);
const defaultValues =
(props.skill &&
Object.assign(
{
startDate: processDate(props.skill.startDate),
endDate: processDate(props.skill.endDate),
},
props.skill,
)) ||
{};
this.props.initialize(defaultValues);
}
render() {
return (
<form
<Field
component={DatePicker}
name="startDate"
label="Start Date"
placeholder="select date"
required
/>
<Field
component={DatePicker}
label="End Date"
name="endDate"
placeholder="End Date"
/>
</form>
);
}
}
and it is validations.js
import {
createValidator,
required,
validDate,
} from 'utils/validation';
import moment from 'moment';
const skillsValidations = createValidator({
startDate: [required, validDate],
endDate: [validDate],
});
export default skillsValidations;
I am using this code but it is not working for compare two dates basically the end date must be greater than start date, I am using date validation but it is not working for me because datepicker validation is lock my calendar after select less than date and calendar is not working then I am not select any date then I have to change calendar month and select date I don't know that is the issue, I don't know what is the problem actually I am using react 16 and I have use react datepicker version 1.1.0
I have tried many logics between two dates compare but there is not logic.
You can make the simple helper function that check the date validation.
checkDateValidation(startDate, endDate) {
// check the dates
if ((new Date(startDate) > new Date(endDate)) || (new Date(endDate) < new Date(startDate))) {
// set date error validation true
} else {
// null or false date error validation
}
}
Here to date from input[type=date] form validation (compare if date end is after date begin)
checkDateValidation(startDate, endDate) {
// check the dates
if (Math.floor((new Date(startDate).getTime() - new Date(endDate).getTime()) / (24 * 3600 * 1000)) < 1) {
// set date error validation true
} else {
// ok pass: end date is sup start date!
}
}
javascriptformvalidationcomparedate
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
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')
},