React-date-picker: When choosing a date from the calendar always will return 00:00:00.

Created on 24 Jun 2020  路  2Comments  路  Source: wojtekmaj/react-date-picker

Hello, when I select a date on the calendar lets say today's date. It will return, Tue Jun 23 2020 00:00:00 GMT-0400 (Eastern Daylight Time). Which is correct but the timestamp is not. I want it to return the exact date/time a user selects the date they choose. Is this possible and how could I accomplish this? Code below.

import React from "react";
import DatePicker from "react-date-picker";

export default () => {
  const [date, onChange] = React.useState(new Date());
  console.log(date);
  return (
    <>
      <DatePicker onChange={onChange} value={date} />
    </>
  );
};

Most helpful comment

Hi @joemark1989
You can try setting the hour,minute and second from a new Date object before setting the value to the state.

const handleOnChange = (dateValue:Date)=>{
  const currentDate = new Date();
  dateValue.setHours(currentDate.getHours());
  dateValue.setMinutes(currentDate.getMinutes());
  dateValue.setSeconds(currentDate.getSeconds());
  setState(dateValue);
}

All 2 comments

Hi @joemark1989
You can try setting the hour,minute and second from a new Date object before setting the value to the state.

const handleOnChange = (dateValue:Date)=>{
  const currentDate = new Date();
  dateValue.setHours(currentDate.getHours());
  dateValue.setMinutes(currentDate.getMinutes());
  dateValue.setSeconds(currentDate.getSeconds());
  setState(dateValue);
}

@HARIKSREEE Thanks :) that did it.

Was this page helpful?
0 / 5 - 0 ratings