ant design - datepicker with time saves with 00:00:00 as time? - reactjs

So im using antd for my design in frontend with React. I want to store an object with datetime in database. I see that antd's Datepicker is capable of that but it always stores in my database with 00:00:00 as time. Date, month year are ok.
I tried to use moment().format('YYYY-MM-DD HH:mm:ss') and save it like that in the database but i get error Uncaught TypeError: date.clone is not a function
This is my datepicker. The issue raises when i try to use my setPickedFrom function from useState. Why is this a problem?
<DatePicker
allowClear={false}
placeholder="Rent from: "
// format="YYYY-MM-DD HH:mm:ss"
disabledDate={disabledDate}
onChange={(e) => onDateClear(e, "from")}
onOk={(date) =>
setPickedFrom(
moment(date).format("YYYY-MM-DD HH:mm:ss"),
"to"
)
}
value={pickedFrom ? pickedFrom : null}
showTime
className="date-picker2"
/>
Saving the dates function (Create Rent)
const createRent = () => {
axios
.post("http://localhost:5000/rents/createRent", {
date_from: pickedFrom,
date_to: pickedUntil,
userId: user.id,
itemId: currentItem.id,
})
.then(() => {
showNotification("Item rented");
setCurrentItem({});
setDifference(null);
setIsModalVisible(false);
setPickedFrom(null);
setPickedUntil(null);
})
.catch((e) => {
showNotification(e.response.data.message, "error");
});
};
I just need to find a way to save date and time in my database in the following format (YYYY-MM-DD HH:mm:ss) because this is the accepted format for my database.

This is what you are looking for
const onOk = (value) => {
console.log("onOk: ", moment().format());
console.log("onOk: ", typeof value);
console.log("onOk: ", value.format("YYYY-MM-DD HH:mm:ss"));
};
<DatePicker format="YYYY-MM-DD HH:mm:ss" showTime={true} onOk={onOK}/>

Related

Get React DatePicker date value in onChange

I'm using react-datepicker, and I'm unable to get the actual date in onChange.
This is my component :
import DatePicker from "react-datepicker";
const DatePick = () => {
return (
<DatePicker
locale="fr"
dateFormat="dd/MM/yyyy"
onChange={(date) => {
console.log(date);
}}
/>
);
};
export default DatePick;
In console.log I'm getting this kind of string Thu Dec 09 2021 00:00:00 GMT+0100 (heure normale d’Europe centrale).
I need to get the date as dd-MM-yyyy in onChange or a date that I can format and use later in a form and submit its value.
Use Below code , it will work like a charm
const [Cdate, setDate] = useState(new Date().toLocaleDateString('fr-FR'));
return (
<>
<DatePicker
dateFormat="dd/MM/yyyy"
value={Cdate}
onChange={(date) => {
const d = new Date(date).toLocaleDateString('fr-FR');
console.log(d);
setDate(d);
}}
/>
</>
);
stackblitz link: https://stackblitz.com/edit/react-nov8it?file=src/App.js
You can use the Date object, to format the date as you would like. For instance :
onChange={(date) => {
const dateString = new Date(date).toLocaleDateString()
console.log(dateString)
}}
You will then get the date formated to your locale time zone. However, if you specified a different format in your DatePicker from your local timezone format, then you can specify it as a parameter for toLocaleDateString:
new Date(date).toLocaleDateString("fr-FR")

Access data from an array of dates

My application can get data from user. For this i have different inputs. One of my inputs is date Picker.
<Form.Item name="Picker" label="date">
<RangePicker
showTime={{ format: "HH:mm" }}
format="YYYY-MM-DD HH:mm"
onChange={onChange2}
onOk={onOk}
/>
</Form.Item>
The issue appear when i try to access data after clicking on submit button. In console i have all data from each input, but from RangePicker, the data is not structured, and i get:
Picker: Array[2]
0: Moment
1: Moment
The problem is that i can access this array, and display on fron end. How to do this?
link to my app: https://codesandbox.io/s/form-methods-ant-design-demo-kbwgk
Try this
import moment from 'moment'
const onFinish = values => {
const startDate = moment(values.Picker[0]).format("YYYY-MM-DD HH:mm");
const endDate = moment(values.Picker[1]).format("YYYY-MM-DD HH:mm");
console.log(startDate, endDate)
};
I got it,
on your rangepicker use
onFinish instead of onOk
<RangePicker
showTime={{ format: "HH:mm" }}
format="YYYY-MM-DD HH:mm"
onChange={onChange2}
onFinish={onFinish}
/>
working as specified
you press Ok twice , so the first onOk still doesnt include the second part of the range
sorry for not giving professional answer
Since you are getting it as an array of moment objects,try using moment js for formatting the moment js according to your needs
https://codesandbox.io/s/form-methods-ant-design-demo-sy4uq
function onOk(value) {
const start = moment(value[0]).format("YYYY-MM-DD HH:mm:ss");
const end = moment(value[1]).format("YYYY-MM-DD HH:mm:ss");
console.log(start, end);
}
const onFinish = values => {
const start = moment(values.Picker[0]).format("YYYY-MM-DD HH:mm:ss");
const end = moment(values.Picker[1]).format("YYYY-MM-DD HH:mm:ss");
console.log(start, end)
};

How to get a custom week value from a WeekPicker in a Form when I submit it

I'm new to ant-design-pro and I'm writing a sample project to help my teammates get more efficient.
Now I faced a problem, I can't get a custom format week value from a WeekPicker in a Form, the week value in the Query String Parameters is week: "2019-12-11T08:45:42.884Z" which is supposed to be YYYYw format, such as week: 201950.
Here is how I defined the Form:
...
<Form onSubmit={this.handleSearch} layout="inline">
...
<FormItem label="">
{getFieldDecorator('week')(<WeekPicker placeholder="周" format={'YYYYw'} />)}
</FormItem>
...
</Form>
...
and here is the function code:
handleSearch = (e: React.FormEvent) => {
e.preventDefault();
const { dispatch, form } = this.props;
form.validateFields((err, fieldsValue) => {
if (err) return;
const values = {
...fieldsValue,
}
...
dispatch({
type: 'listAndtableList/fetch',
payload: values,
});
});
}
The form gets each field value automatically and it didn't notice that I defined a format in the WeekPicker, anyone can help?
I asked an engineer of Ant Financial which company developed ant-design-pro, and then got the answer.
WeekPicker always input or output a moment object, cause there may be a timezone issue, so we need to handle it by ourselves, although we've set a format in it.
Here is the solution:
form.validateFields((err, fieldsValue) => {
if (err) return;
const weekMoment = fieldsValue['week'];
const week = weekMoment.format('YYYYw');
...
});

how to get selected dates in react calendar?

I downloaded react-native-material-calandarview inside my project.
They just give some piece of code to get calendar. https://github.com/NuclleaR/react-native-material-calendarview.
I just selected datesSelection={'range'}, but I dont know where I get the selected dates. If datesSelection={'single'} it return date in
onDateChange={data => {
console.log(data.date);//date selected
}}
More code:
render() {
return (
<Calendar
width={(Dimensions.get('window').width)-32}
height={280}
tileHeight={35}
style={{alignSelf: 'center'}}
topbarVisible={true}
datesSelection={'range'}
firstDayOfWeek="monday"
showOtherDates="none"
currentDate={this.state.today}
selectedDates={this.state.dates}
eventsDates={[]}
eventsColor="#9C27B0"
onDateChange={data => {
//alert(sel_date);
console.log(this.state.data);
}}
onMonthChange={month => {
//alert(month)
console.log(month);
}}
/>
);
}
So the onChange will show you the date the user selects it's up to you to make a function to store these in redux/local state. Same for a range the onChange will return you that range in the argument you're passing to it
So what you can do is
In HTML:
onDateChange={this.onChange}
Component method:
onChange = (date) => { this.setState({ selectedDate: date }) };

React Datepicker( can't get value of input)

I am new in react. I need use react-datepicker
I want to get value of input, when I change date.
If i click on 20th October 2017, i want put 20th October 2017 in my variable.
But the main problem that I should work with component, not with input.
Before I just took value from state. Like this.state.value. But right now it is object(Moment) in state. And this object doesn't have value field.
There is my code:
export default class DatePicker extends Component {
constructor (props) {
super(props);
// this.props.date should looks like "29 November 2017 00:00"
// second argument for moment() it is format of date, because RFC 2822 date time format
this.state = {
date: moment(this.props.value, 'LLL')
};
}
handleChange = (date) => {
// const valueOfInput = this.state.date <--- I want string with date here
console.log('this.state.date',this.state.date);
this.setState({date: date});
};
render() {
return <Form.Field>
<Label>
<Picker
selected={this.state.date}
onChange={this.handleChange}
dateFormat="LLL"
locale={this.props.language}
/>
</Label>
</Form.Field>
Just use this:
handleChange = date => {
const valueOfInput = date.format();
///...
};
Because this datepicker returns a moment.js object!
For more information, look into the moment.js docs here.
Try this
<DatePicker
onChange={(value, e) => this.handleChange(value, e)}
selected={this.state.inputValue} otherProps={here}
/>
// you can access the value field in handleChange by e.target.value
handleChange(value, e) {
console.log(value); // this will be a moment date object
console.log(e.target.value); // this will be a string value in datepicker input field
}
This solved for me by using the following:
handleDateChange = date => {
let selectedDateFromCalender = date.toUTCString();
this.setState({
actualStartDate: selectedDateFromCalender,
});}
<DatePicker
selected={this.state.startDate}
onChange={this.handleDateChange}/>
You can use the following methods as well, choose according to your requirement:
toISOString: "2020-10-05T09:10:38.000Z"
toJSON: "2020-10-06T09:09:16.000Z"
toUTCString: "Thu, 08 Oct 2020 09:11:24 GMT"
If you want to get the new value (once the user clicks on a new date from DatePicker) pass the event to the method.
class MyComponent extends React.Component {
constructor(props) {
this.state = {inputValue: moment(),} // this will set the initial date to "today",
// you could also put another prop.state value there
this.handleChange = this.handleChange.bind(this);
}
}
handleChange(value) {
console.log(value); // this will be a moment date object
// now you can put this value into state
this.setState({inputValue: value});
}
render(){
...
<DatePicker
onChange={(event) => this.handleChange(event)}
selected={this.state.inputValue} otherProps={here} />
...
}
};
The new version of react-datepicker library stopped using a moment.js object, so here is my solution if you want to get a formatted string representation of the date.
First import
import format from "date-fns/format";
Then
<DatePicker
onChange={(value)=>this.handleChange(format(value, "yyyy/MM/dd", {
awareOfUnicodeTokens: true }))}
dateFormat="yyyy/MM/dd"
selected={this.state.inputValue} otherProps={here} />
...
You can use the getTime() helper function on your date object to get the millisecond timestamp for that specific date, which is a JavaScript number data type. Useful for saving data in the backend of your application. For example Flask Peewee ORM requires a timestamp to be saved for the DateTimeField.
const [startDate, setStartDate] = useState(new Date())
<DatePicker
onSelect( date => {
setStartDate(getTime(date))
}
/>
source: https://date-fns.org/v2.0.0-alpha.7/docs/getTime
Combine it with an effect to set the default state value to a timestamp on page load:
useEffect(() => {
setStartDate(getTime(startDate))
}, [])
Otherwise for your UI, you can use the format() helper function to get the string value of the given object, with any given format:
<h1>{format(startDate, "MMMM d, yyyy h:mm aa")}</h1>
source: https://date-fns.org/v2.0.0-alpha.7/docs/format
I have same problem, and I solved it by using the below solution. Please try it:
<p>{this.state.date.toLocaleDateString()}</p>
<input id="tdate" type="date" name="todate" onchange="getToDate(event);">
function getToDate(e){
const tdate = e.target.value;
//alert(tdate);
//console.log(tdate);
//return tdate;
};
here i am trying to access "tdate" variable outside the function.

Resources