Get current date time and future date in Selenium using Java

In our last tutorial, we discussed the technique to read test data from the CSV file. There are some scenarios where we need to send current date and time; even sometimes we need to set a future date too in the application. We can hard code the future date time, even the current one, but that is not the correct standard of test automation. Hence, we will use java methods to get the current date time as well as a future calendar date. It will add dynamicity to our project and also reduces test data dependency.

Date is a class in Java programming, but in some other programming, language Date is considered as a special data type. So, we can quickly get the current date & time by instantiating Date class only.

Let’s start with capturing the current date and time with the help of Java programming.

Get Current Date Time with Java Programming

We first create the instance of Date class. Further, we convert the object of Date class to string to see data in human-readable format. Here is the sample code:

Here is the console output in which you see current date and time.

Current date time

How to format date and time in Java?

The above output is not properly formatted. It needs proper formatting to display the current date and time in a way so that it can be capture appropriately. So here we use another Java class to format the current date and time, thus, we use SimpleDateFormat class.

Here is the sample code:

You can format the date time as per your need by using SimpleDateFormat class. The current date time after formatting would look like below screenshot from the console.

Formatted Current Date Time

How to use Calendar class to get the current date and time in Java?

We can even use Calendar class to get the current date and time in Java. Let’s see how it goes.

See the console output.

Calendar Current Date Time Selenium

How to set future date and time in Selenium?

We will again use Calendar class to get the future date and time. For this, we simply pass arguments inside Calendar’s add() method. Below image depicts different arguments that we can use to customize the date and time.

Calendar class method

The sample program is-

In the above code, I have passed 10 days in advance as a future date. See below console output, it shows 6th March as the future date from today.

Future date time

How to get past date and time in Selenium?

Sometimes we need past date and time as test data in Selenium. We will use a negative sign in arguments to get past data and time. Following sample program display 10 days older date and time.

See console’s screenshot below:

Past date selenium

This was all about current date time handling along with getting future and past date and time using Java programming. These date and time handling help in creating dynamic test data in Selenium WebDriver. It reduces test data dependencies in external sources.

Join Inviul fb group

Leave a Reply