5

I am using React and JSX to return an input field of type "datetime-local". I want the min value to be the date we have today with the current time. I do not know how to write this however.

What I tried :

<input min = {new Date().toLocaleString()}  id = "date" type = "datetime-local"/>

which did not work and no min value is set when I choose datetime .

1 Answer 1

4

The min, max values needs the format: yyyy-MM-ddThh:mm.

new Date().toISOString() returns a string which is always 24 or 27 characters long (YYYY-MM-DDTHH:mm:ss.sssZ or ±YYYYYY-MM-DDTHH:mm:ss.sssZ, respectively.

We can then use string manipulation methods to get the format we want, without the seconds and milliseconds bit :ss.sssZ, for example using String.slice():

 <input 
       min={new Date().toISOString().slice(0, -8)}
       id="date" type="datetime-local" />

Edit infallible-currying-0tqj9

Sign up to request clarification or add additional context in comments.

3 Comments

i had to add this split method: new Date().toISOString().slice(0, -8).split('T')[0]
When I select your option and select from the date time picker the current time, the form does not allow me to submit saying that I should choose 2 hours less. Any ideas?
@Biobrolly there is no <form> in my codesanbox, that validation is likely something implemented somewhere inside your application

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.