Home > front end >  how to set future time in material-ui <textfield type="datetime-local" />
how to set future time in material-ui <textfield type="datetime-local" />

Time:10-31

I want to set the default time of to be 4 hours later to current time so if it is like 31 oct 2021 3:00 am, the default time should show 31 oct 2021 4:00 am and for time like 31 oct 2021 10:00 pm it should show 1 nov 2021 2:00 am

I tried adding to 4 to current hour but it breaks night time.


const currentDate = new Date();

  const dateTime = `${currentDate.getFullYear()}-${currentDate.getMonth()   1}-${currentDate.getDate()}T${
    currentDate.getHours()   3
  }:${currentDate.getMinutes()}`;


<TextField
 id="datetime-local"
 type="datetime-local"
 defaultValue={`${dateTime}`}
 InputLabelProps={{
     shrink: true,
     }}
 InputProps={{ inputProps: { min: `${dateTime}` } }}
 onChange={handleChange}
 />
 </div>

CodePudding user response:

In this case you should add the hours before, even if the hours are higher than 24h, javascript Date will handle this and return the correct one.

const currentDate = new Date();
currentDate.setHours(currentDate.getHours()   4);

Now you can use the Date object.

CodePudding user response:

You can use setHours and getHours methods from Date object.

const currentDate = new Date();
const fourHoursLater = new Date(
  currentDate.setHours(currentDate.getHours()   4)
);

codesandbox

  • Related