Generate random number with current date and time value with Javascript

2

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

I could not get a real example to show here, because I really do not know how to do it.

    
asked by anonymous 02.05.2015 / 02:48

2 answers

2

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

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

alert(datatimeRandom());

DEMO

    
02.05.2015 / 03:08
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 dataAleatoria(date) function generates a random date based on a date passed as a parameter.

If you do not want to pass any date as a 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 both examples, the current date is used to generate another random date.

    
02.05.2015 / 03:03