Generate random date for test data with JavaScript

Siddharth Murugan
4 min readApr 2, 2024

While testing a signup flow or a user data filling page, you may need to generate random Date of Birth to fill in the field. Though we have many packages available to generate random date, let us create our own function to generate date.

Math.random()

Before getting started with date generation function, let us try to understand about Math.random() function. This is an inbuilt function of JavaScript, which return random floating point number greater than 0 but less than 1.

Math.floor()

This is also an inbuilt function of JavaScript, which round off the number to less than the given integer value.

For example,

Math.floor(2.7) 
//Gives 2 as output

Generating random number within specific range

Now, let us generate a random number between a specific range. For example, let us generate a random number ranging between 1 to 12. For this you should follow below formula,

let StartingRange = 1
//Note that ending range isn't inclusive so we need to give next number
let EndingRange = 13
Math.random() * (EndingRange - StartingRange) + StartingRange

Note that the ending number range isn’t…

--

--

Siddharth Murugan
Siddharth Murugan

Written by Siddharth Murugan

Programmer who loves to do things creatively. #automationTester by profession #javascript #nodejs #reactjs

No responses yet