8

I am using react-datetime out of the box.

Right now, I am trying to get the selected date to be saved into my date state.

import DateTime from 'react-datetime';
import '../DateTime.css';

class SomeClass extends React.Component {
  render(){
    return (
      <div>
        <DateTime onChange={this.props.handleDate}/>
      ...

The program above works - it displays a simple box that shows a calendar when someone clicks it.

Here is handleDate method:

  ...
  handleDate(e){
    this.setState({date: e.target.value}, () => console.log(this.state.date))
  };

It works on my regular ol' react-bootstrap component: <FormControl type="date" onChange={this.props.handleDate} /> but when I use DateTime, it says that its value is undefined. "Schedule.js:135 Uncaught TypeError: Cannot read property 'value' of undefined"

I am looking at the APIs from the npm site but don't see any example showing how to get the data. I might be overreading it.

How can I get the value of the selected dates using DateTime? e.target.value does not seem to work on this case.

Iggy
  • 5,129
  • 12
  • 53
  • 87

3 Answers3

9

From the docs: Callback trigger when the date changes. The callback receives the selected moment object as only parameter, if the date in the input is valid. If the date in the input is not valid, the callback receives the value of the input (a string).

Using this information, the handler should look like so:

handleDate(date){
   this.setState({date}); # ES6 
};
Oluwafemi Sule
  • 36,144
  • 1
  • 56
  • 81
  • 1
    Gotcha! Thanks for pointing it out. The code above gives me a `moment` object, but I made a little change and it not worked! `this.setState({date: date._d})` works. The date that I need is inside `_d` key. But your answer led me there, so thanks! – Iggy May 18 '17 at 17:54
  • hello, how can I get selected date timestamp? – Lead Developer Dec 04 '17 at 09:47
  • 1
    Oh, I have got the timestamp by calling date._d.valueOf(). Thanks. – Lead Developer Dec 04 '17 at 09:53
  • @kyl it was helpful. though other way you can get timestamp is by date.unix() – Mutant Oct 10 '18 at 13:17
  • is there a way to store this moment object in sessionStorage? I am trying to store it but it is not storing the entire moment object. – krishna teja Oct 14 '19 at 14:56
  • @krishnateja The [Storage API](https://developer.mozilla.org/en-US/docs/Web/API/Storage/setItem) expects a DOMString to be passed for the value set for a key. You can't store the entire moment object for this reason. Store a string representation of the date object in the session store and parse it back to a moment object when you read it from the store. – Oluwafemi Sule Oct 14 '19 at 18:07
  • @OluwafemiSule Thank you, may I know how can I store the value and send it back to the "value" attribute so that my date picker can understand that format and populate the date I have save before? – krishna teja Oct 14 '19 at 19:32
5

It is late but it will help someone.

import Datetime from 'react-datetime';

 class User extends React.Component {

    constructor(props) {
        super(props);
        this.state = {  
              date: "",
              time: "",
        }
     }
changeDate = (event) => {
     console.log(event.toDate()) // Tue Nov 24 2020 00:00:00 GMT+0400 (Gulf Standard Time)
     console.log(event.format("DD-MM-YYYY")) //24-11-2020
     this.setState({...this.state, date: event.format("DD-MM-YYYY")}) 
}

changeTime = (event) => {
    console.log(event.format("HH-mm-ss a")) //02-00-00 am
    this.setState({...this.state, time: event.format("HH-mm-ss a")})
}

  render() {
    return (
            <div>
              <Datetime
                     id="datepicker"
                           viewMode="days"
                           timeFormat={false}
                            dateFormat="DD-MM-YY"
                            value={this.state.date}
                           onChange={this.changeDate}

                    />


                <Datetime
                     id="timepicker"
                     viewMode="time"
                     dateFormat={false}
                     onChange={this.changeTime}
                     />
            </div>

     )
  }


}
Muhammad Shahzad
  • 9,340
  • 21
  • 86
  • 130
4

Adding to Oluwafemi Sule's answer, to get the date object from moment object you need to use .toDate() and not use any internal properties such as _d as per moment.

Moment uses a technique called epoch shifting that causes this property to sometimes differ from the actual date value that the Moment reflects. In particular if Moment TimeZone is in use, this property will almost never be the same as the actual value that Moment will output from its public .format() function. As such, the values of _d and any other properties prefixed with _ should not be used for any purpose.

To print out the value of a Moment, use .format(), .toString() or .toISOString().

To retrieve a native Date object from Moment, use .toDate(). This function returns a properly shifted date for interaction with third party APIs.

Moment.js Guide

Sachin Kumar
  • 808
  • 3
  • 11
  • 29