Search code examples
javascriptreactjsunix-timestamp

In react, I get too similar unix time stamp in <TextField type="date">


I have two Textfield which set the start date and due date.

here is the code.

const startDateChange = (e) => {
  setStartDate(Math.floor(new Date().getTime(e.target.value) / 1000));
  console.log(startDate);
};

const dueDateChange = (e) => {
  setDueDate(Math.floor(new Date().getTime(e.target.value) / 1000));
  console.log(dueDate);
};

<div>
  <Typography variant="overline" display="block" gutterBottom>Start Date</Typography>
  <TextField id="standard-basic" type='date' style={{margin:3}} onChange={startDateChange} />
</div>
<div>
  <Typography variant="overline" display="block" gutterBottom>Due Date</Typography>
  <TextField id="standard-basic" type='date' style={{margin:3}} onChange={dueDateChange} />
</div>

However, every time I change these two individual inputs, I always get similar numbers (Unix timestamp), even I set the due date as the year 2033.

Therefore, When I render with converted Unix timestamp number, I get the same date of each of these two inputs, which are the date of Today.

I need bits of help.


Solution

  • Try to move the e.target.value in the Date constructor:

    const startDateChange = (e) => {
      setStartDate(Math.floor(new Date(e.target.value).getTime() / 1000));
      console.log(startDate);
    };
    
    const dueDateChange = (e) => {
      setDueDate(Math.floor(new Date(e.target.value).getTime() / 1000));
      console.log(dueDate);
    };