How to Add Date and Time Picker using only one tag in HTML?


Incorporating date and time pickers into web forms is a common requirement for many web developers. While you might think that adding date and time pickers might be a complicated task and you might have to use JavaScript libraries. But to your surprise, this is a relatively easy task using tags provided by HTML. This can significantly reduce the amount of code and time required to implement date and time pickers in your web application.

Syntax

<input type = "value" ... />

The <input> tag is an interactive element in HTML whose main purpose is to take different forms of inputs from the user. The type attribute of the tag specifies what kind of input should the user enter.

Approach

We are going to make use of the input tag to get the desired date and time picker. To have a date picker we can make use of the following tag

<input type="date">

while for having a time picker we can use of the following tag

<input type="time">

However this will result in two tags to get the desired time and date picker. To get the desired result with only one tag we are going to make use of the datetime-local type value. The tag will look as follows −

<input type="datetime-local">

There are two main sections in this code −

  • <head>

  • <body>

The <head> section is relatively simple and self explanatory as it only contains some meta-data about the document. Moving over to the <body> section, it is composed of some elements but the one that you should pay attention on is the input field. The input field is where the magic happens. We have used the "datetime-local" attribute which we have talked about before to create the <input> tag. Using this attribute signifies the browser to create a combined date and time picker control.

Example

The following is the complete code which we are going to cover in this example −

<!DOCTYPE html>
<html>
<head>
   <title>How to add date and time picker using only one tag in HTML?</title>
</head>
<body>
   <h4>How to add date and time picker using only one tag in HTML?</h4>
   <div>
      <p>Date and Time Picker </p>
      <input type="datetime-local" />
   </div>
</body>
</html>

Conclusion

In this article we saw how we can use the input tag to get date and time picker in HTML. We saw at two diiferent alternatives, one where we can get the desired result using two tags and the other where we can get the desired output with only a single tag.

Updated on: 28-Mar-2023

780 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements