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 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"
/>
Update:
If I remove giving datepicker options from html, it works but I want to set default options like autoclose and all.
I am using https://nkalinov.github.io/ng2-datetime/ for a "from to" datepicker. I am able to set default date for the from datepicker whereas the to datepicker shows choose date until I choose a date. I want to set today as the default date for the to datepicker.
constructor() {
const today = new Date();
this.dateInterval = 7;
const dateObj: any = moment(today).subtract(this.dateInterval, 'days');
this.dateFrom = new Date(dateObj);
this.defaultPickerOptions = {
autoclose: true,
dateFormat: "%Y-%m-%d %H:%i",
enableTime: false,
enableDate: true,
endDate:today
};
this.toPickerOptions = {...this.defaultPickerOptions, startDate:this.dateFrom,defaultViewDate:today};
this.dateTo = today;
};
handleDateFromChange(date) {
this.dateFrom = date;
this.toPickerOptions = {
...this.toPickerOptions,
startDate:this.dateFrom,
}
};
handleDateToChange(date) {
this.dateTo = date;
}
html --->
<datetime [ngModel]="dateFrom" (ngModelChange)="handleDateFromChange($event)" [datepicker]="defaultPickerOptions" [timepicker]="false"></datetime>
<span><b>to:</b></span>
<datetime [ngModel]="dateTo" (ngModelChange)="handleDateToChange($event)" [timepicker]="false" [datepicker]="toPickerOptions" ></datetime>
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();
};
This question is similar to knockoutjs databind with jquery-ui datepicker, but instead of the jQueryUI datepicker, I would like to use one of the Bootstrap datepickers.
The API for the Bootstrap datepicker is different from jquery-ui, and I am having some trouble wrapping my head around making it work with knockout.js. I have created a jsFiddle to try it out.
It seems like the Bootstrap datepicker could be much simpler to use because it does not independently store the date. However, I would like to know how whether the jsFiddle is the appropriate way to use the Bootstrap datepicker widget with knockout.js i.e.
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
ko.utils.domNodeDisposal.addDisposeCallback(element, function() {
$(element).datepicker("destroy");
});
},
update: function(element, valueAccessor) {
}
};
Here is a sample of how you could accomplish this with the datepicker that you are using:
ko.bindingHandlers.datepicker = {
init: function(element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function(event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function(element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
if (widget.date) {
widget.setValue();
}
}
}
};
It did not look like there was any destroy functionality, so I removed that piece. This handles the widgets changeDate event to update the view model, when a user changes the date. The update function handles when the view model is changed to update the widget.
If you want to bind the value to a non-observable, then it would take a little more code. Let me know if that is something that you need to support.
http://jsfiddle.net/rniemeyer/KLpq7/
my current version is a mix between the already shown solutions:
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
var unwrap = ko.utils.unwrapObservable;
var dataSource = valueAccessor();
var binding = allBindingsAccessor();
//initialize datepicker with some optional options
var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
$(element).datepicker('update', dataSource());
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
value(event.date);
}
});
},
update: function (element, valueAccessor) {
var widget = $(element).data("datepicker");
var value = ko.utils.unwrapObservable(valueAccessor());
//when the view model is updated, update the widget
if (widget) {
widget.date = value;
if (widget.date) {
widget.setValue();
$(element).datepicker('update', value)
}
}
}};
The accepted answer didn't work for me with the current version of the date picker. The input wasn't being initialized with the value of the observable. I made an updated binding, to which I added this:
$(element).datepicker('update', dataSource());
That seems to do the trick.
Here's an updated fiddle that uses the latest available date picker, Bootstrap, jQuery, and Knockout: http://jsfiddle.net/krainey/nxhqerxg/
Update:
I experienced some difficulty with the date picker not playing nicely with the observable when a user would edit the value in the text field manually. The tool would immediately parse the date, and plug the result into the input field.
If the user tried to edit 10/07/2014, for example, and used the backspace or delete to remove a number (10/0/2014), the resulting value would be parsed immediately and inserted into the text input. If the value was, for a moment, 10/0/2014, the picker would shift the calendar to 09/30/2014, and plug that value into the text field. If I tried to edit the month, and the value was, for a moment, 1/7/2014, the picker would shift to January 7, 2014, and plug that value in to the text field.
You can see that behavior in this fiddle:
http://jsfiddle.net/krainey/nxhqerxg/10/
I had to update my binding with a special handler to detect focus, and bind a one-time blur event to get it to handle manual edits correctly.
$(element).on("changeDate", function (ev) {
var observable = valueAccessor();
if ($(element).is(':focus')) {
// Don't update while the user is in the field...
// Instead, handle focus loss
$(element).one('blur', function(ev){
var dateVal = $(element).datepicker("getDate");
observable(dateVal);
});
}
else {
observable(ev.date);
}
});
The fiddle referenced in the original answer has been updated to reflect this:
http://jsfiddle.net/krainey/nxhqerxg/
Here is what I Ended up
ko.bindingHandlers.datepicker = {
init: function (element, valueAccessor, allBindingsAccessor) {
//initialize datepicker with some optional options
var options = {
autoclose: true,
format: 'yyyy-mm-dd',
}
//var options = allBindingsAccessor().datepickerOptions || {};
$(element).datepicker(options);
//when a user changes the date, update the view model
ko.utils.registerEventHandler(element, "changeDate", function (event) {
var value = valueAccessor();
if (ko.isObservable(value)) {
var myDate = event.date;
var month = myDate.getMonth() + 1;
var monthText = month;
if (month < 10)
monthText = "0" + month;
var day1 = parseInt(myDate.getDate());
var dayText = day1;
if (day1 < 10)
dayText = '0' + day1;
value(myDate.getFullYear() + '-' + monthText + '-' + dayText);
}
});
},
update: function (element, valueAccessor) {
var widget = $(element).data("datepicker");
//when the view model is updated, update the widget
if (widget) {
widget.date = ko.utils.unwrapObservable(valueAccessor());
widget.setValue(widget.date);
}
}};
There is a much simpler way to get bootstrap-datepicker.js and knockout.js working together. Typically the initialization of the datepicker inputs is invoked during/after the page load. However when knockout.js updates the value binding, the datepicker is not updated correctly with the new value and so when you focus on the datepicker input it defaults to 01-Jan-2001.
All you have to do is to destroy and reinitialise the datepicker inputs after any knockout.js value bindings are updated as per the ViewModel method below, which sets up a mapped object to be edited.
self.showEditOrderForm = function (data) {
ko.mapping.fromJS(data, self.entity);
self.mode('edit');
$('#edit-dateordered').datepicker('destroy');
$('#edit-dateordered').datepicker({
format: 'dd-M-yyyy',
title: 'Select Date',
weekStart: 1,
todayHighlight: true,
autoClose: true,
endDate: '0d'
});
};