Skip to main content

Create Current, Past and Future Times

Creating dynamic times can be essential for various testing scenarios, such as scheduling events, setting deadlines, or validating time-related functionalities. DevAssure's Advanced Code Blocks feature allows users to write custom JavaScript code to generate current, past, and future times.

Learn more about Advanced Code Blocks

Function to create the time using a delta parameter

const timeOptions = {
hour: '2-digit',
minute: '2-digit',
hour12: true
};

const currentDate = new Date();
const futureDate = new Date(currentDate);

if (deltaInHours != 0) {
let diff = Number(currentDate.getHours()) + Number(deltaInHours);
futureDate.setHours(diff);
}

const formattedFutureTime = futureDate.toLocaleString('en-US', timeOptions);

The code above defines a function to create a time based on a delta parameter, which represents the number of hours to add or subtract from the current time. Here's a breakdown of how it works:

  1. Time Options Object: The timeOptions object specifies the formatting options for the time, including the hour, minute, and whether to use a 12-hour clock.
  2. Current Date: The currentDate variable holds the current date and time
  3. Future Date: The futureDate variable is initialized to the current date. If the deltaInHours parameter is not zero, the code adjusts the hour of the futureDate by adding the deltaInHours value.
  4. Formatted Time: The formattedFutureTime variable holds the formatted time string based on the specified options.

Function to create the time using a delta parameter

Sample DevAssure code

Sample DevAssure code