How to Change Format in HTML Datepicker

Naila Saad Siddiqui Feb 15, 2024
How to Change Format in HTML Datepicker

This article is about an HTML input element datepicker and specific issues it has while selecting the date format.

Change Format in HTML Datepicker

When HTML5 added date input, many people thought it would give users a familiar, interactive, and friendly way to enter a date on a website.

However, this recent addition has fallen short of expectations, and the inconsistent nature of the user’s input remains a major contributing factor.

The date input attribute was initially intended to be a form element where users could select values using a datepicker. However, the implementation of the datepicker, which varies from browser to browser, is the issue.

It means that even though you (as a web designer) may have intended to let users select dates using the datepicker with the format YYYY/MM/DD and designed your HTML validations accordingly.

Still, when a user accesses the webpage through his system’s browser, he may see a completely different set of options depending on the system’s default date settings and the browser used.

Currently, HTML5 does not contain a rule permitting web designers to alter the format in which the date element selects values. To change the date format the user must enter, designers had to find alternatives to the date element’s rigidity.

Alternatives for Datepicker

Let’s say we want to create a website where users can enter their birthdays, and the format that the user must enter is YY-MM-DD. Since the date element does not permit us to alter the date format, how will we be able to accomplish this using it?

One of the fastest ways to achieve this is using the jQuery datepicker Widget.

jQuery Datepicker Widget

jQuery provides us with a datepicker widget with plenty of different functionalities that we can use to customize the date calendar on our website. One of the functionalities to be focused on in this article is changing the date format as per our choice.

For implementing this widget, we will first create the HTML side of this code by creating a <input> type of date and assigning it an id value:

<body>
    <h3>Click to select a date :</h3>
    <input type='text' id='myDatePicker' />
</body>

Then we will add the corresponding jQuery code in the head section of the webpage:

<script type="text/javascript">
    $(function () {
        $('#myDatePicker').datepicker({ dateFormat: 'yy-mm-dd' });
    });
</script>

Make sure to include the jQuery library files in your webpage. The output will be like this.

change format in html datepicker - output

The above output shows that the selected date is automatically converted into the specified format. Therefore, it is the simplest way to change the date format according to our needs and requirements.