Generate random date for test data with JavaScript
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…