Display Date off by one in react - reactjs

I am using the html input type date on a form in react. Previously when encountering issues with the javascript date object and getting it to display correctly, I used the method of .replace(/-/g, "/") and the day passed in would be displayed correctly.
I am making a new app and trying the same thing and receiving the following error basically copying and pasting lines of code.
The specified value "2021/07/06" does not conform to the required format, "yyyy-MM-dd".
So apparently you are required to do a timezone offset to get the date object to correctly display in react?
Here is what i am trying to do to get a proper date to display in the value of the date picker:
<input
type='date'
name='startDate'
value={startDisplay != null && startDisplay}
id=''
onChange={(e) => {
setStartDate(e.target.value);
setStartDisplay(
Intl.DateTimeFormat({
year: "numeric",
month: "numeric",
day: "numeric",
})
.format(new Date(startDate))
.replace(/-/, "/")
.replace(/-/, "/")
);
}}
/>
I'm wondering if there is a fix that allows the replace method to work, or if someone can help me write a function for setDisplayDate that properly uses timezoneoffset.
or should I just suck it up and add the date picker library?

Related

RangeError: Invalid Time Value after incorporating local storage

I'm working on a forum and using a form that the user fills out I'm storing data as an object inside an array. The data I'm storing includes the title of a topic, the message, the author and the date. That data is stored inside a topic array which I'm mapping on screen so the user can see all current topics, who created them and the date in which they were created. I also started to use localStorage so I can save my data and test to make sure everything looks good after my page refreshes.
const [topic, setTopic] = useState(() => {
const topicJson = localStorage.getItem("topic");
return topicJson ? JSON.parse(topicJson) : [];
});
const updatedTopic = [
...topic,
{
title: title,
message,
author: "Dagger",
date: new Date(),
},
];
setTopic(updatedTopic);
};
That's the code that I'm using which works as intended however when I map through the array to post the data on screen, I'm having trouble with showing the date. I'm using date-fns because it displays the date exactly how I want it.
Example: 2/19 9:39PM. That's how I want the date to look on screen and using date-fns has been the only thing I've found that makes it look that way.
{topic
.sort((a, b) => b.date - a.date)
.map(({ date }, index) => (
<tr>
{<td>{format(date, "M/dd h:mma")}</td>}
</tr>
))}
That's the code I'm using to map through the array to show the date. Before adding localStorage it worked fine. When I remove the format and show the code as date it works but including format gives me this error:
throw new RangeError('Invalid time value');
// Convert the date in system timezone to the same date in UTC+00:00 timezone.
// This ensures that when UTC functions will be implemented, locales will be compatible with them.
I think your are using Date object to store date and JSON.stringify cant handle Date object. You should to use Date method.
Easy way just save not Date object but ISO string.
date.toISOString()
And in table:
{<td>{format(parseISO(date), "M/dd h:mma")}</td>}

Change date format of mat-date-picker using date pipe

I have tried to change the value of selection in angular material date picker to YYYY-MM-DD format as follows:
In dateInput event of the field I call a function which will change the format of date using date pipe and set value back. However, the format doesnt change.
HTML Code
<input matInput placeholder="Stop Date" [matDatepicker]="stopDate" (dateInput)="OnStopDate($event.value)" formControlName="stopDate">
<mat-datepicker-toggle matSuffix [for]="stopDate"></mat-datepicker-toggle>
<mat-datepicker #stopDate></mat-datepicker>`
TS Code
`OnStopDate(Value){
const update= this.datepipe.transform(Value, 'YYYY-MM-dd'); //this value is being update
this.myForm.controls.stopDate.setValue(update,{emitEvent: false}); // the value is not being set in yyyy-mm-dd but in mm-dd-yyyy
}
I did see a solution provided using MomentDateAdapter as here. Is this the only solution proceed and why ?

react-day-picker changing default date format prevents entering date

I have just started using the react-day-picker library. I have the following code sandBox which is a fork of the range with 2 inputs example,
https://codesandbox.io/s/w6vnlox29l
I have it working the way I want but I want to input the dates as MM/DD/YYYY instead of the default format, YYYY-MM-DD. When I add the following attributes
<DayPickerInput
value={from}
format="M/D/YYYY"
formatDate={formatDate}
parseDate={parseDate}
placeholder="MM/DD/YYYY"
onDayChange={this.handleFromChange}
dayPickerProps={{
selectedDays: [from, { from, to }],
modifiers,
disabledDays: {
after: new Date(),
},
numberOfMonths: 2,
toMonth: new Date(),
}}
/>
I can no longer correctly enter the date in the input field the date. When I remove the format, formatDate and parseDate attributes the date picker input functions the way I expected. I have read the documentation but think I may be missing something simple. How can I use the input text box and date picker with dates formatted as MM/DD/YYYY?

React-datepicker changes date but not time

I'm using Moment.js with react-datepicker. It works as intended in terms of the date transformation to ISO-8601, but I can't get it compliant with the time.
Here's my component:
Stated initially:
this.state = {
from: moment().subtract(7, "days"), // Default 1 week back
to: moment(), // Current date
};
The component itself:
<DatePicker
dateFormat="DD-MMM HH:mm"
dropdownMode="select"
selected={this.state.from}
onChange={this.handleFromChange}
/>
And the onchange trigger:
handleFromChange(date) {
this.setState({
from : date
});
}
I think my issue is the dateFormat; The DD-MMM are easily transformed to ISO-8601 by calling using the ECMAScript function toISOString() before posting it to some backend services. But how do I get the time to go with it?
The user(myself, testing) can chance the time on the datepicker itself, but it won't register in the state. Simply it will just pick the current time, or current time 1 week ago(as per the moment from/to initial states). The date, i can change also, but the time remains the same(current time).
How do I change the dateFormat so it takes the time input from the user? How do I make it ISO 8601 compliant per default in the dateFormat attribute?
Edit: I just tested with setting "from" to subtract 5 minutes at such:
this.state = {
from: moment().subtract(5, "minutes"),
to: moment(), // Current date
};
And it formats it correctly when I post it. Seems strange. It must be related to the onChange function then?
Try using dateFormat="dd-MMM hh:mm" and change onChange function to this to avoid error.
handleFromChange(date) {
this.setState({
from : date || ""
});
}

MomentJs invalid date from datepicker

I Am trying to format a date from react datepicker, the value going in is 1441062000000
onChangeStartDate: function(value) {
this.setState({
startDate: moment(value)
})
},
When I check the date in dev tools I get a moment invalid date, can anyone tell me how I can create a date from the value?
I'm using the value 1443135600000 with format, but still getting invalid date:
onChangeEndDate: function onChangeEndDate(value) {
console.log(moment(value, ConfigProvider.getKey('dateFormat')));
You might need to pass the format as a second argument to moment - in case of react date picker, it defaults to 'x', e.g. unix timestamp:
this.setState({
startDate: moment(value, 'x')
})
If you omit the second argument, moment tries to parse the input by looking for ISO 8601 formats, but a unix timestamp will cause this algorithm to fail. That's why you need to specify the format explicitly.
The other way would be to configure your date picker to emit changes in an IS 8601 compliant format, for example format='YYYY-MM-DD'.

Resources