PrimeNg 12 p-calendar UTC issue - calendar

I've a problem with PrimeNg Calendar component. I need to remove UTC from selected value in calendar. Selecting a date in the calendar component, the form value is:
Wed Jun 01 2022 00:00:00 GMT+0200 (Ora legale dell’Europa centrale)
so when i call a rest service passing this value, it is converted into:
"2022-05-31T22:00:00.000Z"
I know it's a problem related to UTC but I can't find a way to remove UTC setting attributes into p-calendar.
Is there a way to do this? Or it's possibile to manage the selected value into a directive?
I'm using PrimeNg 12.2.16

For me I made a solution with a directive and date offset correction:
import { Calendar } from 'primeng/calendar';
import { Directive } from '#angular/core';
#Directive({
selector: '[utcCalendar]',
})
export class UtcCalendarDirective {
constructor(private pCalendar: Calendar) {
// Function was taken from
// https://github.com/primefaces/primeng/blob/master/src/app/components/calendar/calendar.ts
pCalendar.updateModel = (value) => {
pCalendar.value = value;
if (pCalendar.dataType == 'date') {
// Changes
const date = new Date(pCalendar.value);
date.setTime( date.getTime() + (-date.getTimezoneOffset())*60*1000 );
pCalendar.onModelChange(date);
}
else if (pCalendar.dataType == 'string') {
if (pCalendar.isSingleSelection()) {
pCalendar.onModelChange(pCalendar.formatDateTime(pCalendar.value));
}
else {
let stringArrValue = null;
if (pCalendar.value) {
stringArrValue = pCalendar.value.map((date: any) => pCalendar.formatDateTime(date));
}
pCalendar.onModelChange(stringArrValue);
}
}
};
}
}
And then when I do value.toISOString() It will give a date like '2022-09-12T00:00:00.000Z'.
Tested with forms. Outputs like onSelect() and some other functionality won't be changed but you can improve this code.

Related

Why is this date sum not being displayed correctly in react?

I have the following component which simply gets the current date, adds a year to it, and should render it. But its rendering a weird number
import React from 'react'
class Calendario extends React.Component {
constructor(props) {
super(props);
this.state = {
birth_date : new Date(),
years_to_live: 10,
death_date: ""
};
}
componentDidMount() {
var death_date = this.state.birth_date.setFullYear(this.state.birth_date.getFullYear() + 1) //this is should result in the current date +1
this.setState({ death_date : death_date});
}
render() {
return (
<div>
<p>Hello world!</p>
<p>{this.state.death_date}</p>
</div>
)
}
}
export default Calendario;
It for some reason renders
1610227797517
Instead of
Sat Jan 09 2021 22:21:12 GMT+0100 (Central European Standard Time)
Whats the issue?
You are getting back a date as an integer, since you are using a javascript Date object for birth_date.
You can parse it back to a date to do what you need to (format, etc.)
var dt = new Date(1610227797517);
console.log(dt);
// output: Sat Jan 09 2021 16:29:57 GMT-0500 (Eastern Standard Time)
But, you should be able to use a format on the object itself
console.log(this.state.death_date.toDateString());
// output: Sat Jan 09 2021

How to use dateSetAction() and dismissedAction() methods in DatePickerAndroid?

The documentation is not enough to understand nor there is any example to understand. Why & how to use dateSetAction() and dismissedAction() methods in DatePickerAndroid?
These are basically internal getter functions/methods that are called internally to determine whether the date has been selected or not. These two methods are defined in the DatePickerAndroid class as:
static get dateSetAction() {
return 'dateSetAction';
}
static get dismissedAction() {
return 'dismissedAction';
}
You can visit this page to populate yourself about these methods.
Simple explanation:
dateSetAction is a type of action that tells you the date has been selected in the datepicker.
dismissedAction is also another type of action that tells you the datepicker dialog has been dismissed/closed.
Example:
async openAndroidDatePicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
date: new Date(2020, 4, 25)
});
if (action === DatePickerAndroid.dismissedAction) {
console.log('Date picker has been dismissed/closed');
} else if (action === DatePickerAndroid.dateSetAction) {
console.log('Date has been selected');
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}
If the user picked a date, Object containing action, year, month (0-11), day. If the user dismissed the dialog, the Promise will still be resolved with the action being DatePickerAndroid.dismissedAction and all the other keys being undefined. Always check whether the action before reading the values.
async openAndroidDatePicker() {
try {
const {action, year, month, day} = await DatePickerAndroid.open({
// Use `new Date()` for current date.
// May 25 2020. Month 0 is January.
date: new Date(2020, 4, 25)
});
if (action !== DatePickerAndroid.dismissedAction) {
// Selected year, month (0-11), day
}
} catch ({code, message}) {
console.warn('Cannot open date picker', message);
}
}

react-datetime-YouCanBookMe error time and update state

I'using this library for react time picker: https://github.com/YouCanBookMe/react-datetime
But now I have 2 problems.
The time (Am, Pm, HH:mm) in timepicker doesnt'work , because it doesn't change, it remain to 12 : 00 AM
How correctly update state? because if I handle onChange (input manual write), it receive string, that I can't parse and it is invalid date.
My code is:
import DateTime from 'react-datetime';
var moment = require('moment');
handleChangeDate(propertyName, date) {
const event = Object.assign({}, this.state.event);
if (typeof date === 'string') {
date = moment(date);
}
event[propertyName] = data.format('DD/MM/YYYY HH:mm');
this.setState({ event: event });
}
and in Render() I have compoment:
<DateTime dateFormat={"dddd, MMM. Do YYYY, HH:mm (hh:mm a)"} value={this.state.event.to} onChange={this.handleChangeDate.bind(this, 'to')}/>
What is wrong?
check in below link.
Customized calendar will solve your problem.
https://github.com/YouCanBookMe/react-datetime#customize-the-appearance
After choose date in calendar then click on date. It will show the edit option for time.
Example Link
https://codepen.io/simeg/pen/YppLmO
Let it try

Restrict post dates into Full Calendar

I´m developing Full Calendar like this, but instead of creating events I just get it from the database.
So now I developing Backend to receive days of the week of an event like this:
As you can see I receive booleans within days of the week
Now I want to restrict if one of this days come false, calendar doesn´t allow me to do that
JS Function:
function isGreaterThanToday(date) {
return date < hoy ? false : true;
}
function updateAssignedEvent(event, delta, revertFunc) {
if (!isGreaterThanToday(event.start)) {
mostrarError("Cant post an event today or before today.");
revertFunc();
return;
}
event.start = $.fullCalendar.moment(moment($.fullCalendar.moment(event.start.format())._i));
event.end = event.end ? $.fullCalendar.moment(moment($.fullCalendar.moment(event.end.format())._i)) : event.start;
event.color = getTareaCalendarioColor(event.tipoResponsable,
event.estatusTarea,
event.start,
event.end.diff(event.start, 'hours') <= 24 ? event.start : event.end);
updateEvent(event).then(function(data) {
if (!data.success) {
revertFunc();
return;
}
event.end = event.end !== event.start ? event.end.add(1, 'day') : event.end;
$calendar.fullCalendar('updateEvent', event);
}, function(error) {
revertFunc();
});
}
As you can see I have a function calledfunction isGreaterThanToday(date), I use it to restrict post an event today or before today. I want to do something like this, but I don´t have an idea of how can I call these booleans and compare for example Sunday of the calendar with Sunday of boolean receive. Can anyone help me there? Regards
For example into my function I add:
if (event.accion.agendarDomingo != true) {
mostrarError("Sunday is not allowed");
revertFunc();
return;
}
But how can I compare with my event.start and event.end DAY?
To get day of week using moment.js use 'e' as a format. result will be 0..6 Monday to Sunday.
event.start.format('e');
To check if the time is passed use isAfter function:
If nothing is passed to moment#isAfter, it will default to the current time.
moment(event.start).isAfter();
Now these two validation constraints combined would look like this:
function isDateValid(date) {
return date.format('e') !== "6" && moment(date).isAfter();
}

Objects are not valid as React child

I have a function which calculates the date from a unix timestamp
_getTime(time) {
var dateTime = new Date(time*1000);
console.log(dateTime);
return dateTime
},
The function is used in this
render: function() {
return (
{this.state.daily.map(day => {
return (
<div key={day.time} className="key col-md-12">
<div className="col-md-3">{this._getTime(day.time)}</div>
</div>
);
);
},
This returns Invariant Violation: Objects are not valid as a React child (found: Thu Oct 20 2016 00:00:00 GMT+0200 (CEST)). If you meant to render a collection of children, use an array instead or wrap the object using createFragment(object) from the React add-ons. Check the render method ofApp.
I am aware of there questions with the same error message, but I can't seem to figure out a solution for my problem.
Plain javascript:
_getTime(time) {
var dateTime = new Date(time*1000).toString();
console.log(dateTime);
return dateTime
},
Using moment.js
_getTime(time) {
var dateTime = moment(time*1000).format('YYYY-MM-DD HH:mm:ss');
console.log(dateTime);
return dateTime
},

Resources