Generate random time within a range

Asked

Viewed 1,074 times

-2

I have a function that generates the current time, time +12hs and time +24hs.

I need him to run a random schedule within that 12-hour and 24-hour window.

I got the following:

//DEFINE HORARIO DE BRASILIA
date_default_timezone_set('America/Sao_Paulo');
//HORARIO AGORA
$agora = date('d/m/Y H:i:s', time());

//HORÁRIO AGORA +12 HORAS
$dataliberacao12= date('d/m/Y H:i:s', strtotime('+12 hours', time()));

//HORÁRIO AGORA +24 HORAS
$dataliberacao24= date('d/m/Y H:i:s', strtotime('+24 hours', time()));

//RESULTADOS
echo 'Horário que concluiu: '.$agora.'<br/>';
echo 'Horario liberção 12h: '.$dataliberacao12.'<br/>';
echo 'Horario liberção 24h: '.$dataliberacao24;

2 answers

7


No, I couldn’t use it right +12 hours?

$dataGerada = date('d/m/Y H:i:s', strtotime('+' . random_int(720, 1440) . ' minutes', time()));

If you only want an hour, without changing the minutes (keeping the same minutes/seconds of the current time) it would be even simpler:

$dataGerada = date('d/m/Y H:i:s', strtotime('+' . random_int(12, 24) . ' hours', time()));

The random_int(12, 24) would generate an hour between +12 and +24, exactly what you described in the question. Use the random_int(720, 1440) would also generate a time between +12 hours (720 minutes) to +24 hours (1440 minutes), but would generate minutes.

  • show, I used the first option, gave it right, thank you!

3

You can generate a random date and time using the function Rand() or mt_rand() by setting the minimum and maximum (strtotime of min and max dates).

//DEFINE HORARIO DE BRASILIA
date_default_timezone_set('America/Sao_Paulo');
//HORARIO AGORA
$agora = date('d/m/Y H:i:s', time());

//HORÁRIO AGORA +12 HORAS
$dataliberacao12= date('d/m/Y H:i:s', strtotime('+12 hours', time()));

//HORÁRIO AGORA +24 HORAS
$dataliberacao24= date('d/m/Y H:i:s', strtotime('+24 hours', time()));

// Horario aleatorio entre os intervalos
$dataAleatoria = rand( strtotime(date('m.d.Y H:i:s', strtotime($dataliberacao12))), strtotime(date('m.d.Y H:i:s', strtotime($dataliberacao24))));
$dataAleatoria = mt_rand( strtotime(date('m.d.Y H:i:s', strtotime($dataliberacao12))), strtotime(date('m.d.Y H:i:s', strtotime($dataliberacao24))));

echo 'Horario aleatorio: '.date("d/m/Y H:i:s", $dataAleatoria ).'<br>';

//RESULTADOS
echo 'Horário que concluiu: '.$agora.'<br/>';
echo 'Horario liberção 12h: '.$dataliberacao12.'<br/>';
echo 'Horario liberção 24h: '.$dataliberacao24.'<br/>';
  • thanks for the answer. tested here, it is generating the randomized day tbm

  • I edited the answer @Leandromarzullo, try it this way

  • opa, it worked out tbm, vlw!!!

Browser other questions tagged

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