Skip to content

Instantly share code, notes, and snippets.

@mparker17
Last active March 4, 2016 20:36
Show Gist options
  • Save mparker17/cd1fc32b647b3b62582c to your computer and use it in GitHub Desktop.
Save mparker17/cd1fc32b647b3b62582c to your computer and use it in GitHub Desktop.
Random PHP dates
<?php
/**
* Generates a random date.
*
* Essentially generates a random, positive integer and interprets it as a
* number of seconds from the start of the UNIX epoch (i.e.: 1970-01-01 00:00:00
* UTC).
*
* This function checks $min and $max: if you try to pass $min < 0, the function
* will use 0 as the minimum; likewise, if you pass $max > getrandmax(), the
* function will use getrandmax() as the maximum.
*
* @param int $min
* The smallest datetime we should generate (in UNIX time). If you pass a
* number less than 0, it will be automatically corrected to 0. If you run
* this function on a system where getrandmax() will return a number
* sufficiently high that it will be after the current UNIX timestamp, then
* you can set this argument to the value of time() and $max = NULL (or $max =
* getrandmax()) to generate a date in the future.
* @param int|null $max
* The largest datetime we should generate, or NULL to use the value of
* getrandmax(). If you pass a number greater than getrandmax(), it will
* automatically be corrected to 0. Set this to the current value of time()
* and $min = 0 to generate a date in the past.
*
* @return \DateTime
* A datetime object representing this random date.
*/
function randomDatetime($min = 0, $max = NULL) {
// Don't generate a date before the start of the UNIX epoch.
$min = (int) $min;
$min = ($min < 0) ? 0 : $min;
// We can't generate a random integer bigger than getrandmax().
$rand_max = getrandmax();
if (is_null($max) || $max >= $rand_max) {
$max = $rand_max;
}
else {
$max = (int) $max;
}
$random_seconds_since_epoch = rand($min, $max);
$answer = new DateTime();
$answer->setTimestamp($random_seconds_since_epoch);
return $answer;
}
/**
* Generates a random date in the future.
*
* Note this function makes the assumption that getrandmax() will return a
* number sufficiently high that it will be after the current UNIX timestamp.
*
* @return \DateTime
* A datetime object representing this random date.
*/
function randomDatetimeInFuture() {
$current_datetime = time();
$rand_max = getrandmax();
return randomDatetime($current_datetime, $rand_max);
}
/**
* Generates a random date in the past.
*
* @return \DateTime
* A datetime object representing this random date.
*/
function randomDatetimeInPast() {
$current_datetime = time();
return randomDatetime(0, $current_datetime);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment