Article Bites

We write about tech, news, and things that can interest fellow website owners.

Native datetime-local input: add minimum value programmatically

Jan 15, 2024 | Web Development

We’re working on a web application at the moment, where we use React.js for the frontend, and Django for the backend. We decided to use the native datetime-local input element for selecting a date and time in one of the form. We wanted to set a minimum value for our calendar part of the input.

The Lowdown on Minimum Values:

Why bother with a minimum value, you ask? Well, imagine preventing users from picking dates and times from the Stone Age. A minimum value ensures they’re on the right track, especially when you’re dealing with scheduling or time-sensitive tasks.

Let’s Get Hands-On:

We were already using moment.js library to handle and format date and time, so we thought it would be useful in this situation as well.

The issue we ran into was that the date and time input needed a very specific date and time format.

But let’s not get ahead ourselves…

First we grabbed the date we needed as a variable:

const twoDays = moment().add(2, "days");
// Wed Jan 17 2024 13:22:11 GMT+0100 (Netherlands Standard Time)

Next idea was to format that value as an ISO string:

const formattedTwoDays = twoDays.toISOString();
// 2024-01-17T13:22:11.055Z

But oops, that did not work with our date and time input.

It seemed like the following format was needed, without the seconds and milli seconds in the end .

// 2024-01-17T13:22

Make sense, because our input can not handle seconds, and milliseconds.

So we did the following next, and formatted our date and time to the exact format we needed:

const twoDaysFormatted = twoDays.format("YYYY-MM-DDT05:00");
// "2024-01-17T05:00"

And with that our calendar input had the right minimum date set.

Conclusion:

By adding a minimum value to your datetime-local input, you’re not just being cool – you’re making sure your users get it right the first time.

Tip: You can add a maximum value as well, so you can make sure the users can’t select a date in the far future. It all depends on your use-case of course.

Skip to content