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"
/>
Related
i have a dynamic form that contains multiple date fields. i don't know how many date fields will be there in future. if i select one date from date picker it shows in all fields the same date as shown in the picture.
i don't want to use state because i don't know the exact number of date fields in my form in future as it is dynamic. is there any alternative for state or any solution for it with state?
in the given picture i used state just to show the issue, now i want to use something by which can get date from multiple fields
like this here second field picked the same date of first field
if (item.element == "DatePicker") {
let i_id = item.id;
return (
<View style={styles.input}>
<View style={styles.layout}>
<Text>{item.label}</Text>
<Text>{this.state.cdate}</Text>
<Button title="Date" onPress={showDatePicker} />
<DateTimePickerModal
isVisible={this.state.setDatePickerVisibility}
mode="date"
onConfirm={handleConfirm}
onCancel={hideDatePicker}
/>
</View>
</View>
);
}
const showDatePicker = () => {
this.setState({
setDatePickerVisibility: true,
});
};
const hideDatePicker = () => {
this.setState({
setDatePickerVisibility: false,
});
};
const handleConfirm = (date) => {
Moment.locale('en');
let dates = Moment(date).format('DD-MM-YYYY')
this.setState({
cdate: dates,});
hideDatePicker();
};
I'm trying to get the current day/month/year in a React Native App. I am new at this, so I have many doubts about the implementation.
I tried to follow the following solution, but does not work for me:
currentDay: new Date(),
console.log('Date:'+this.state.currentDay ,);
console.log('Day: '+this.state.currentDay.getDay() , 'Month: ' + this.state.currentDay.getMonth(), 'Year :'+ this.state.currentDay.getYear());
Most easiest way to install npm install moment --save
Moment is a JavaScript date and time manipulation library for parsing, validating, manipulating, and formatting dates.
You can simply import it in your code:
import moment from 'moment';
var now = moment().format();
if you just want current date and output in your desired format, you can use moment with format function
var currentDate = moment().format("DD/MM/YYYY");
Result
30/03/2019
You can change date format according to your requirement using Moment library
You can refer the following documents read about how to use moment and what function they will provide
https://momentjs.com
https://devhints.io/moment
Install the moment package: npm i moment
import moment from 'moment';
var dateAndTime= moment().format("DD/MM/YYYY HH:mm:ss")
output: 15/11/2019 15:33:23
var date= moment().format("DD/MM/YYYY")
output: 15/11/2019
(this output is only for current date, of course).
const onPressDateValidation = () =>{
const currentDate ='2022-02-20'
// const currentDate ='2022-02-25'
// const currentDate ='2022-02-26'
const fromDate ='2022-02-20'
const toDate = '2022-02-25'
console.log("Umesh_______1 ", currentDate);
console.log("Umesh_______2 ", fromDate);
if ( moment(currentDate).isSameOrAfter(fromDate) ) {
if( moment(currentDate).isSameOrBefore(toDate)){
alert("Show your Ad either it's Banner Ad or Video Ad")
}else{
alert(" Ad is Expired")
}
} else {
alert("Ad is not started yet")
}
}
You need to add a getDate() function after newDate() .. i.e. var date = new Date.getDate()
The following code example (which should clarify implementation purposes) is illustrated on AboutReact.com, where you can run the code online.
import React, { Component } from 'react';
import { StyleSheet, View, Alert, Text } from 'react-native';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
//default value of the date time
date: '',
};
}
componentDidMount() {
var that = this;
var date = new Date().getDate(); //Current Date
var month = new Date().getMonth() + 1; //Current Month
var year = new Date().getFullYear(); //Current Year
var hours = new Date().getHours(); //Current Hours
var min = new Date().getMinutes(); //Current Minutes
var sec = new Date().getSeconds(); //Current Seconds
that.setState({
//Setting the value of the date time
date:
date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
});
}
render() {
return (
<View
style={{
flex: 1,
justifyContent: 'center',
alignItems: 'center',
}}>
<Text
style={{
fontSize: 20,
}}>
Current Date Time
</Text>
<Text
style={{
fontSize: 20,
marginTop: 16,
}}>
{this.state.date}
</Text>
</View>
);
}
}
Obviously, the style is flexible and you could omit the time element of the code sample (but it may be useful to other users)..
Hope this helps
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}
/>
}
/>
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>
I have two input text box startdate and enddate
<input type="text" id="startdate"/>
<input type="text" id="enddate"/>
I need two simple things
On click of startdate and selection of start date, need to update
end date with +7 days.
Format needed is mm/dd/yyyy
So if any one click startdate with 01/01/2015 i.e 1st January 2015 , than end date should automatically set with 01/08/2015
On selection of startdate, I need to get enddate open automatically.
The datepicker Library I had used is ALLOYUI datepicker version 3.0
http://alloyui.com/examples/datepicker/
Can anyone please write down code please.
Guys
<script>
var datefrom;
YUI().use(
'aui-datepicker',
function(Y) {
datefrom = new Y.DatePicker(
{
trigger: '#dpfrom',
popover: {
zIndex: 1
},
calendar: {
//maximumDate : new Date(today.getFullYear(),today.getMonth()+1,today.getDate()),
minimumDate : new Date(),
},
on: {
selectionChange: function(event) {
}
}
}
);
}
);
//console.log(james);
</script>
I found the may to set minimum and maximum date but still i donot have the way to set end date +7 days to current date.
Please find similar and working one for me. Please customize it if you need anything.
<input class="form-control" type="text" id="selecteddate" placeholder="Day, Mon dd, yyyy"></input>
YUI().use(
'aui-datepicker',
function(Y) {
var datepicker = new Y.DatePicker(
{
trigger: 'input',
popover: {
zIndex: 1
},
after: {
selectionChange: function(event) {
event.preventDefault();
Y.log(datepicker.getSelectedDates());
var myDate=Y.DataType.Date.addDays(new Date(datepicker.getSelectedDates()),+6);
if (myDate.isValid()) {
$("#selecteddate").val(myDate);
}
}
}
}
);
}
);
Date.prototype.isValid = function () {
// An invalid date object returns NaN for getTime() and NaN is the only
// object not strictly equal to itself.
return this.getTime() === this.getTime();
};