Reputation: 1469
I have a form and I want to set an input text field to display the current date and time:
I have the following function:
const getDateTime = () => {
let tempDate = new Date();
let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
const currDate = "Current Date= "+date;
return (
{currDate}
);
}
for the input text field: inside a constructor, I set the state:
reportStartDate: '',
the hypertext is set as follow:
<div className="form-group">
<label htmlFor="reportStartDate">Report Start Date:</label>
<input type="text" name="reportStartDate" className="form-control" placeholder="Report Start Date" value={this.state.reportStartDate} onChange={e => this.change(e)} />
</div>
How do I get the current date and time to display within the text field?
Upvotes: 1
Views: 4078
Reputation: 33994
If I understand your question correctly you need to set current date and time to input field when the input field is shown initially if so,
First in the constructor set reportStartDate with current date and time so that the input field will initially show current date before user selects the preferred date and time
constructor(props){
super(props);
this.state = {
reportStartDate: getDateTime()
}
}
Now change getDateTime little bit in the return line
const getDateTime = () => {
let tempDate = new Date();
let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
return date;
}
Make sure you modify the state in change event handler function using setState when user changes the date time
Upvotes: 1
Reputation: 5455
Use the setState() function - see this for more information
const getDateTime = () => {
let tempDate = new Date();
let date = tempDate.getFullYear() + '-' + (tempDate.getMonth()+1) + '-' + tempDate.getDate() +' '+ tempDate.getHours()+':'+ tempDate.getMinutes()+':'+ tempDate.getSeconds();
const currDate = "Current Date= "+date;
this.setState({ reportStartDate: currDate})
}
Upvotes: 2