JavaScript for Optimizers: Adding a DateTime Picker

Jeroen Wiersma
By
May 10, 2021 ·

We’ve all been there: the frustrating task of manually adding the date in a form.

Now, I don’t know about you, but when I am looking for the date format, my brain goes into overdrive. Are you going for MM/DD/YYYY? What if we want YYYY-MM-DD instead? How many days does February have again?

This blog post will take you through some JavaScript functions that will help optimize your code by adding a DateTime Picker input field to your forms.

Business Case: Adding a DateTime Picker

In this hypothetical scenario, we arrive at the following hypothesis:

Because we saw that the completion rate of the date field is low, we expect that adding a datetime picker for supported browsers will cause an increase in leads. We’ll measure this using completion rates.

To test this hypothesis, we’re going to apply the changes below:

Adding a datetime picker to an input field
Adding a datetime picker to an input field

The Code Used in the Experiment

Now let’s get to the fun part!

To execute the change, we run the JavaScript code below on the testing page. Copy the code and try it out for yourself!

var dateInput = document.querySelector("#date");
var supported = true;
var test = document.createElement("input");
try {
  test.type = "date";
} catch (e) {
  supported = false;
}
if (supported) {
  dateInput.setAttribute("type", "date");
  dateInput.setAttribute("value", getFormattedDate(0));
  dateInput.setAttribute("min", getFormattedDate(-1));
  dateInput.setAttribute("max", getFormattedDate(1));
}
function getFormattedDate(changeYear) {
  var today = new Date();
  var dd = String(today.getDate()).padStart(2, "0");
  var mm = String(today.getMonth() + 1).padStart(2, "0");
  var yyyy = today.getFullYear() + changeYear;
  formattedDate = yyyy + "-" + mm + "-" + dd;
  return formattedDate;
}

Breakdown of the Code

1. New Syntax

The breakdown starts by going over all the new syntax in the example above. Since this article is part of a series, make sure you check the syntax’s complete documentation in the other articles in the series (including this article published on the Convert blog).

try {} catch (error) {} is a statement that you can use to try specific code and catch errors if needed. When the code runs, and no error occurs, it will skip the catch.

If it returns an error, it will catch it. The script will now execute the code between the catch body. Because it passes the error in the function, you can console.log it to find the specific problem.

Usually, when you run into an error, the code will stop executing. This statement will allow you to continue with your script when you expect an error.

.type is a method that sets the attribute value “type” of an element in the DOM.

.getDate() is a method that returns the day of a date object. It will return the day as a number.

.padStart(targetLength, padString) is a method that allows us to pad a string with a different character for the amount we want. You pass down the number of times that you want to pad a string in the targetLength argument. You pass down the string that is used as padding in the padString argument. It will take the padString length into account when padding it.

.getMonth() is a method that returns the month of date object as a number. It starts counting at 0, so this will be January. Number 11 will be December.

String() is a method that tries to convert the argument that is passed down to a string value. This method is usually used when you want to convert numbers to strings.

.getFullYear() is a method that returns the year of a date object.

return is a common and important statement when working with functions. Sometimes you need to run a function to get data and use it somewhere else. A return state in a function will end the function execution and return whatever is right of the statement.

learn how you can use javascript to develop test for any a/b testing tool

2. Logic

var dateInput = document.querySelector("#date");

We start by selecting the date input fields with the querySelector method. We added the id=”date” to our input field to use #date as our selector. We assign the element to our newly declared dateInput variable.

var supported = true;

Then we declare the variable supported. We assign the boolean true to our newly declared variable. We will change this value later on if the browser does not support a datetime picker.

var test = document.createElement("input");

We need to create an input field that we will use purely for checking if this type is supported. We do this with the .createElement method.

We pass down “input” as a string to create the input element. We save this element to the newly declared test variable.

We will use the following try statement to check if our change is supported:

try {

Begin by writing the try keyword. We open the statement with a curly bracket.

The function will try everything between these brackets. It will just run the code to see if an error occurs.

test.type = "date";

We can test if the date type is supported by setting the date type to our test input field. If no error occurs, we know that the browser supports it.

} catch (e) {

Then, we write our catch statement after the closing bracket. The part between the curly brackets will run when we catch an error.

By putting an “e” as the argument, we can use this in our catch statement. You can use this to console.log the specific error, for example.

supported = false;

If we catch the error, we need to change the variable supported to false. We will use this value later on, to determine if we want to execute the change or not.

}

Then, close out the catch statement with a closing bracket.

if (supported) {

We will use the value of the variable supported to run an if statement. If the variable holds true, it will run the statement. This way, we make sure that the browser is not unsupported.

dateInput.setAttribute("type", "date");

To add a datetime picker, we simply need to add the attribute type with the value date to our dateInput variable. Depending on the browser, it will now show an icon that you can click to select dates.

dateInput.setAttribute("value", getFormattedDate(0));

We also want to add a default date to the input field. You can set the default date of a date field by adding a value attribute that holds the date as a string.

Use the function getFormattedDate, which we have defined, to get today’s date in the correct format. The function can add or remove years by inputting a number as the argument when calling it.

dateInput.setAttribute("min", getFormattedDate(-1));

This way, we can use this line to set the minimum date of the selector to 1 year before today. You can do this by passing -1 as the argument. This will restrict the user from selecting a date that is before the minimum date.

dateInput.setAttribute("max", getFormattedDate(1));

Do the same for the maximum amount the users can select. Set the maximum year one year from now by passing down a “1” as the argument.

}

Close the if statement with a curly bracket. This change will now be visible on the input field.

We still need to define the function that is used in our if statement. We want this function to return a date in the following format: yyyy-mm-dd.

function getFormattedDate(changeYear) {

To achieve this result, start by using the function keyword to define one. We give the name getFormattedDate to our function.

To have a little bit of control over what kind of date gets returned, set changeYear as the argument.

We can use this as the keyword in the function body to control what is passed down when the function is called.

var today = new Date();

Start this function body by creating a new date object. The moment the new date object is created will be the time that is stored. This means that we can assign our new object to the newly declared today variable.

var dd = String(today.getDate()).padStart(2, "0");

The getDate method gets the days of our date. When the days are in the single digits, it will add a 0 before the number with the padStart method.

Otherwise, this would be the wrong format for our input field. We also need to convert the number to a string so we can concatenate our numbers later on. Otherwise, the program will use addition.

var mm = String(today.getMonth() + 1).padStart(2, "0");

Here, we use the getMonth to get the months of today’s date. We make a small correction by adding 1 to the number that is returned. Then, we padded the number with a zero if the number is one digit. This method ensures we have the right format for the month data.

var yyyy = today.getFullYear() + changeYear;

Next, we get today’s year with the getFullyear method. Use the number that is passed down the function to change the year.

formattedDate = yyyy + "-" + mm + "-" + dd;

Then, we combine all our variables to a formatted date using string concatenation.

return formattedDate;

We return the formattedDate variable so it can be used by the function caller.

}

Lastly, we close our function with a curly bracket and end our script. The script can use this function before it is declared because functions are hoisted to the top of the code. The same happens to variables. The code might run a little bit faster if you move the formattedDate function above the if statement.

3. Exercise

So, now that you have the entire process laid out, all that’s left is for you to try it out. And don’t forget to have fun with it!

Go ahead and change the input field, so the min field contains the date that is exactly two years from today. Then, add a max date two years from now. Good luck!

Adding a minimum and maximum year to a datetime picker
Adding a minimum and maximum year to a datetime picker

Can’t figure it out? Send me a message on LinkedIn, and I will help you out!

And in case you’ve missed our last article, check out how to insert a total discount section on your site and other advanced conversion optimization techniques.

Mobile reading? Scan this QR code and take this blog with you, wherever you go.
Originally published May 10, 2021 - Updated July 17, 2024
Written By
Jeroen Wiersma
Jeroen Wiersma
Jeroen Wiersma
Jeroen Wiersma is a technical marketeer and founder of GrowthPenguin.
Edited By
Carmen Apostu
Carmen Apostu
Carmen Apostu
Head of Content at Convert

Start your 15-day free trial now.

  • No credit card needed
  • Access to premium features

You can always change your preferences later.
You're Almost Done.
Convert is committed to protecting your privacy.

Important. Please Read.

  • Check your inbox for the password to Convert’s trial account.
  • Log in using the link provided in that email.

This sign up flow is built for maximum security. You’re worth it!