Generate random number with date value and current time with Javascript

Asked

Viewed 1,792 times

2

I would like to know how to generate a random number, based on the current date and time value, using Javascript.

I couldn’t get a real example to show here, because I really don’t know how to do this.

2 answers

2

See the following example:

function dataAleatoria(dataIni) {
    var dataAtual = new Date();
    return new Date(dataIni.getTime() + Math.random() * (dataAtual.getTime() - dataIni.getTime()));
}

var minhaDataAleatoria = dataAleatoria(new Date(2012, 0, 1));

The function dataAleatoria(date) generates a random date based on a date passed as a parameter.

If you do not want to pass any date as parameter, you can do as shown in the code below:

function dataAleatoria() {
    var dataIni = new Date(2012, 0, 1);
    var dataAtual = new Date();
    return new Date(dataIni.getTime() + Math.random() * (dataAtual.getTime() - dataIni.getTime()));
}

var minhaDataAleatoria = dataAleatoria();

Note that in the two examples, the current date is used to generate another random date.

2


Another way to generate this value is to multiply the current date and time (in seconds) by a random value of Math.random():

function datatimeRandom() {
    return((new Date().getTime() / 1000) * Math.random());
}

alert(datatimeRandom());

DEMO

Browser other questions tagged

You are not signed in. Login or sign up in order to post.