DatePicker date input with custom format - datepicker

I want to stote dates in my state using redux-form. I use react-datepicker. To make the datepicker compatible with my redux-form i write:
import React, { PropTypes } from 'react';
import DatePicker from 'react-datepicker';
import moment from 'moment';
import 'react-datepicker/dist/react-datepicker.css';
const MyDatePicker = ({ input, meta: { touched, error } }) => (
<div>
<DatePicker
{...input} dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
The problem is that when i choose date i want it to show as DD-MM-YYYY but i want the date to be saved in my state with the YYYY-MM-DD HH:MM:SS format. How to do this? I use the moment's format function but it did not seem to work

You should use the value lifecycle methods that redux-form provides for this.
Use parse to format the value coming from react-datepicker for storage and format to parse the value from the store back for react-datepicker to present it. Example:
function formatDateForInput(storedDate) {
// the returned value will be available as `input.value`
return moment(pickedDate).format('right format for your input')
}
function parseDateForStore(pickedDate) {
// the returned value will be stored in the redux store
return moment(storedDate).format('desired format for storage')
}
<Field
component={ MyDatePicker }
format={ formatDateForInput }
parse={ parseDateForStore }
/>
If this does not work for your, I would recommend checking if you need to put a custom onChange handler between the DatePicker and input prop provided by redux-form. Because it could be that the values DatePicker is using to call onChange are ones that redux-form does not understand. Like this:
const MyDatePicker = ({ input, meta: { touched, error } }) => {
const onChange = event => {
const pickedDate = event.path.to.value;
input.onChange(pickedDate);
}
return (
<div>
<DatePicker
dateFormat="YYYY-MM-DD"
selected={input.value ? moment(input.value) : null}
onChange={ onChange }
/>
{
touched && error &&
<span className="error">
{error}
</span>
}
</div>
);
}
MyDatePicker.propTypes = {
input: PropTypes.shape().isRequired,
meta: PropTypes.shape().isRequired
};
export default MyDatePicker;
Hope this helps!

If i am understanding correct you just need 2 different formats for same date one on UI and other to save ? moment(date).format('DD-MM-YYYY') and moment(date).format('YYYY-MM-DD HH:MM:SS') will give you both formats date.

Just use the prop dateFormat="dd/MM/yyyy"
Example :
<DatePicker
selected={startDate}
onChange={date => handleChange(date)}
dateFormat="DD/MM/YYYY"
/>

I used the below props -mask, inputFormat and format - to change the default format to "yyyy-MM-dd" format.
The format code "yyyy-MM-dd" is important, play around this to find the desired format.
Example:
<LocalizationProvider dateAdapter={AdapterDateFns} >
<DatePicker
label="SomeDate"
{...register("details_received_date")}
mask="____-__-__"
inputFormat="yyyy-MM-dd"
format="yyyy-MM-dd"
value={someDate}
onChange={(newValue) => {setSomeDate(newValue);}}
renderInput={(params) => <TextField {...params} />}
/>
</LocalizationProvider>
This will display in the front end and provide the value as well in the desired format.
Hope this helps.

Try this
inputFormat="DD/MM/YYYY"
const [value, setValue] = useState(null);
<LocalizationProvider dateAdapter={AdapterDayjs}>
<DatePicker
label="DatePicker Example"
value={value}
onChange={(newValue) => {
setValue(newValue);
}}
renderInput={(params) => <TextField {...params} />}
inputFormat="DD/MM/YYYY"
/>
</LocalizationProvider>

Related

MUI Datepicker onChange event working with manual input but not when clicking date

I've been toying around with this for a while to no avail.
When the user inputs a date manually into the text field, that onChange event fires and everything works as I want it to. When the user clicks on a date from from datepicker, nothing at all happens.
I'm still getting used to using MUI fields in Controllers to suit React Hook Form, but I'm not sure what I'm doing incorrectly.
const { handleSubmit, control, register } = useForm();
const [selectedDate, setSelectedDate] = React.useState(null);
const handleDateChange = (date) => {
console.log(date)
setSelectedDate(date);
};
<form onSubmit={handleSubmit(submitForm)}>
<MuiPickersUtilsProvider utils={DateFnsUtils}>
<Controller
control={control}
name={"newEffectiveDate"}
defaultValue={null}
render={() => (
<KeyboardDatePicker
inputVariant="outlined"
disableToolbar
format="MM/dd/yyyy"
margin="normal"
id="date-picker-inline"
label="Date picker inline"
value={selectedDate}
onChange={date => handleDateChange(date)}
KeyboardButtonProps={{
"aria-label": "change date",
}}
/>
)}
/>
</MuiPickersUtilsProvider>
</form>
Any help would be much appreciated!
Turns out, I just needed to add the autoOk prop to the KeyboardDatePicker component...

Configure Date Format of React Input Date-type

I have an <Input/> from reactstrap that accepts date. I'm using moment.js to parse my date. Although I want the format of the dates to be localized.
This is my code:
<Input
bsSize="lg"
type="date"
name="date"
value={moment(this.state.birthDate).locale('en').format("LLLL")}
onChange={this.handleBirthDateChange}
/>
Although when I try to select my date input, it doesn't accept the date chosen.
Moment will be an object, you'd need to format it to the ISO standard string which is the HTML's date type
Try this moment().format('YYYY-MM-DD')
Sandbox: https://codesandbox.io/s/musing-mclaren-tuqz0
This might help you get started
import React from 'react'
import ReactDOM from 'react-dom'
import moment from 'moment'
import {Input} from 'reactstrap'
import 'bootstrap/dist/css/bootstrap.css'
export class App extends React.Component {
constructor(props) {
super(props)
this.state = {
birthDate: moment()
.locale('en')
.format('YYYY-MM-DD')
}
}
handleChange = e => {
this.setState({birthDate: e.target.value})
}
render() {
let {birthDate} = this.state
return (
<>
<Input
bsSize="lg"
type="date"
name="date"
value={birthDate}
onChange={this.handleChange}
/>
</>
)
}
}
ReactDOM.render(<App />, document.getElementById('root'))

Vue didn't show date Value

I am trying to get and modify a date value, I get the date value from mongoose, I correctly get the value, and I can modify it correctly, but moongoose give me the date in this format :
YYYY-MM-DDT00:00:00.000Z,
So I want to change the display value with an Italian format, like: DD/MM/YYYY.
I have try with this:
<template>
<div class="col">
<span> Date </span>
<input
:value="birth" v-on:input="birth = $event.target.value" type="date" />
</div>
</template>
<script>
import DataService from '#/services/DataService'
import ClickToEdit from '#/components/ClickToEdit'
import moment from 'moment'
export default {
name: 'Options',
data: function() {
return {
birth: '',
}
},
methods: {
async getAllInfo() {
var userInfo = await DataService.getInfoFromSomeWhere({
})
this.birth = this.frontEndDateFormat(userInfo.data.user[0].birth)
},
frontEndDateFormat: function(date) {
return moment(date, 'YYYY-MM-DDT00:00:00.000Z').format('DD/MM/YYYY')
}
},
mounted() {
this.getAllInfo()
}
}
</script>
The date was correctly changed, but the vue page didn't display the date value, and I think is because the default input value display the date in this way :
gg/mm/aaaa
I have already try to change the frontEndDateFormat method with gg/mm/aaaa instead of DD/MM/YYYY, but If I do this I have a strange value in input, like gg/00/amamamama ( I think the problem is related to moment).
So I tried to use :
<input :value="birth" v-on:input="birth = $event.target.value" type="date" v-model="date" />
But If I get an error:
:value="birth" conflicts with v-model on the same element because the
latter already expands to a value binding internally
What am I doing wrong? Thank you

Material UI date picker Date format React

I can't see to format the Material UI Date picker in a React app??
When a user selects a date, I want it to format to be MM/DD/YYYY. I looked up a couple answers but it's not clear where the function to change the format is supposed to go??? For some reason, there is no clear function/location of where it goes online>>
DatePicker component
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* `DatePicker` can be implemented as a controlled input,
* where `value` is handled by state in the parent component.
*/
export default class DateSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
controlledDate: null,
openSnackbar: false,
snackbarText: {
dateconf: 'Date has been entered!'
}
};
}
formatDate(date){
return (date.getMonth() + 1) + "/" + date.getFullYear() + "/" + date.getDate();
}
handleChange = (event, date) => {
console.log('we are in a handle change in date select', event, date)
this.setState({
controlledDate: date,
});
// this.setState({
// openSnackbar: true
// })
};
render() {
console.log('state and props in date select', this.state, this.props)
return (
<DatePicker formatDate={this.formatDate}
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
);
}
}
///THE PARENT COMPONENT
handleDatePicker = (name, date) => {
console.log('handling date change', name, date)
this.setState(prevState => ({
currentRow: {
...prevState.currentRow,
purchase_date: date
},
purchase_date: date,
actionType: 'date'
}))
this.setState({
openSnackbar: true
})
}
<DateSelect
hintText="Purchase date"
value = {this.state.purchase_date}
onChange={this.handleDatePicker}
/>
You need to use formatDate function to format the date and time in date picker
formatDate --> This function is called to format the date displayed in the input field, and should return a string. By default
if no locale and DateTimeFormat is provided date objects are formatted
to ISO 8601 YYYY-MM-DD.
<DatePicker
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
formatDate={(date) => moment(new Date()).format('MM-DD-YYYY')}
/>
if you do not pass any format on the date it seems that the min and max date are not working.
For more details material-ui/DatePicker
Straight from the documentation of DatePicker. Try this
<DatePicker
inputFormat="MM/dd/yyyy"
hintText="Date of purchase"
hintStyle={{color:'whitesmoke'}}
inputStyle={{ color:'whitesmoke'}}
value={this.state.controlledDate}
onChange={this.props.onChange}
/>
inputFormat should usually do the trick. You can change it around the way you want and it can be used for dateTimePicker as well.
For example,
inputFormat="yyyy/MM/dd"
or any other way
formatDate did not work for me in V4. documention suggest inputFormat and worked properly.I found usage example here
<DatePicker
openTo="year"
views={["year", "month", "day"]}
value={toDate}
onChange={(newValue) => {setToDate(newValue);}}
maxDate={maxdate}
minDate={minDate}
format="DD-MM-YYYY"
/>

How to disable past dates in material-ui Date picker?

I'm using material-ui Date-Picker. How to disable past days before today's date?
import React from 'react';
import DatePicker from 'material-ui/DatePicker';
function disablePastDays(date) {
//code here to disable past days
}
const calendar = () => (
<div>
<DatePicker shouldDisableDate={disablePastDays}/>
</div>
)
material-ui's DatePicker accepts minDate prop. So you might want this:
const today = new Date();
<DatePicker minDate={today}/>
Use disablePast.
<DatePicker
disablePast
/>
They have it since v1.0.0-beta.10.
We can give minDate as props to the DatePicker material UI component
Create a state using usestate and then pass the state value into the props as below
const [startMinDate, setStartDate] = useState(new Date())
<DatePicker
required
label="Date"
disablePast
minDate = {startMinDate}
/>
I am using import DatePicker from '#mui/lab/DatePicker'; library of version "#mui/lab": "^5.0.0-alpha.66"
Below code works fine for me
<DatePicker
disablePast
value={checkout.rideDate}
onChange={(newValue) => { // your code of onChange functionality}
/>
}
/>