Creating Random Numbers in JavaScript using the Date Constructor

When using Math.random() in JavaScript we create a random number between 0 and less than 1. What if we want to create a random number that is greater than 1, how do we go about that?

In this blog post, we will create a random number leveraging the Date constructor along with Math.random().

const createNewRandomNumber = new Date(
      new Date().valueOf() - Math.random() * 1e12
    )
      .valueOf(); 
      
      console.log(createNewRandomNumber); //792477825949

In the above code snippet, we leverage the Date constructor using new Date() and within it we get the current date and time as milliseconds new Date().valueOf() since Epoch (i.e. January 1, 1970). We then utilize Math.random() and multiply it by 1e12 in order to generate a random number in milliseconds, which can go up to a trillion and then subtract the results of the multiplication from the current date time that we created using new Date().valueOf(). The result is then outputted in a Date object and then outputted in numeric format valueOf().

TypeScriptJavaScript
Avatar for Muhammad Asfour

Written by Muhammad Asfour

I am a Full Stack Developer with over 5 years of experience. I have worked with different tech stacks such as: Groovy/Java, PHP, .NET/.NET Core (C#), Node.js, React, Angular, and Vue.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.