如何使用php生成两个日期之间的随机日期?

时间:2022-11-13 14:17:49

I am coding an application where i need to assign random date between two fixed timestamps

我正在编写一个应用程序,需要在两个固定时间戳之间分配随机日期

how i can achieve this using php i've searched first but only found the answer for Java not php

我首先搜索了php,但只找到了Java而不是php的答案,如何才能实现这个目标呢

for example :

例如:

$string = randomdate(1262055681,1262055681);

11 个解决方案

#1


78  

PHP has the rand() function:

PHP具有rand()函数:

$int= rand(1262055681,1262055681);

It also has mt_rand(), which is generally purported to have better randomness in the results:

它还具有mt_rand(),一般认为其结果具有更好的随机性:

$int= mt_rand(1262055681,1262055681);

To turn a timestamp into a string, you can use date(), ie:

要将时间戳转换为字符串,可以使用date(),即:

$string = date("Y-m-d H:i:s",$int);

#2


34  

If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.

如果给定的日期是日期时间格式,那么使用最简单的方法是将两个数字转换为时间戳,然后将它们设置为随机数生成器的最小和最大边界。

A quick PHP example would be:

一个简单的PHP示例是:

// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
    // Convert to timetamps
    $min = strtotime($start_date);
    $max = strtotime($end_date);

    // Generate random number using above bounds
    $val = rand($min, $max);

    // Convert back to desired date format
    return date('Y-m-d H:i:s', $val);
}

This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.

该函数使用zombat建议的strtotime()将时间描述转换为Unix时间戳,并使用date()从生成的随机时间戳中获得有效的日期。

#3


24  

You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.

你可以用一个随机数来确定一个随机的日期。获取日期之间的0到天数之间的随机数。然后在第一次约会的时候加上这个数字。

For example, to get a date a random numbers days between now and 30 days out.

例如,为了得到一个日期,从现在到30天的随机数字。

echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));

#4


8  

Here's another example:

这是另一个例子:

$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;

$daystep = 86400;

$datebetween = abs(($dateend - $datestart) / $daystep);

$randomday = rand(0, $datebetween);

echo "\$randomday: $randomday\n";

echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";

#5


7  

Another solution using PHP DateTime

另一个使用PHP DateTime的解决方案。

$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.

$start和$end是DateTime对象,我们将其转换为Timestamp。然后我们使用mt_rand方法来获取它们之间的随机时间戳。最后,我们重新创建一个DateTime对象。

function randomDateInRange(DateTime $start, DateTime $end) {
    $randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
    $randomDate = new DateTime();
    $randomDate->setTimestamp($randomTimestamp);
    return $randomDate;
}

#6


4  

The best way :

最好的方法:

$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );

#7


2  

The amount of strtotime in here is WAY too high.
For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:

这里的时间太长了。对于任何在1971年之前和2038年之后有兴趣的人来说,以下是一个现代、灵活的解决方案:

function random_date_in_range( $date1, $date2 ){
    if (!is_a($date1, 'DateTime')) {
        $date1 = new DateTime( (ctype_digit((string)$date1) ? '@' : '') . $date1);
        $date2 = new DateTime( (ctype_digit((string)$date2) ? '@' : '') . $date2);
    }
    $random_u = random_int($date1->format('U'), $date2->format('U'));
    $random_date = new DateTime();
    $random_date->setTimestamp($random_u);
    return $random_date->format('Y-m-d') .'<br>';
}

Call it any number of ways ...

可以用各种方式来称呼它……

// timestamps
echo random_date_in_range(157766400,1489686923);

// any date string
echo random_date_in_range('1492-01-01','2050-01-01');

// English textual parsing
echo random_date_in_range('last Sunday','now');

// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);

As is, the function requires date1 <= date2.

因此,函数需要date1 <= date2。

#8


2  

By using carbon and php rand between two dates

在两个日期之间使用碳和php rand。

$startDate = Carbon::now();
$endDate   = Carbon::now()->subDays(7);

$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');

OR

$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');

#9


0  

Simplest of all, this small function works for me I wrote it in a helper class datetime as a static method

最简单的是,这个小函数适用于我,我将它作为一个静态方法写在一个helper类datetime中

/**
 * Return date between two dates
 *
 * @param String $startDate
 * @param String $endDate
 * @return String
 *
 * @author Kuldeep Dangi <kuldeepamy@gmail.com>
 */
public static function getRandomDateTime($startDate, $endDate)
{
    $randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
    return date(self::DATETIME_FORMAT_MYSQL, $randomTime);

}

#10


-1  

Pretty good question; needed to generate some random sample data for an app.

很好的问题;需要为应用生成一些随机样本数据。

You could use the following function with optional arguments to generate random dates:

您可以使用以下函数和可选参数来生成随机日期:

function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
    return $result;
}

sample input:

样例输入:

echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00

echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>'; 
//1942/Jan/19 00:00 AM

echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January

echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00

echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00

echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00

readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.

不同的应用程序对读者的要求也不尽相同,总的来说,希望这个功能是一个方便的工具,您需要为应用程序生成一些随机的日期/示例数据。

Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .

请注意,该函数最初处于调试模式,因此将其更改为$mood="",而不是在生产中调试。

The function accepts:

函数接受:

  1. start date
  2. 开始日期
  3. end date
  4. 结束日期
  5. format: any php accepted format for date or time
  6. 格式:任何php接受的日期或时间格式
  7. timezone: name or offset number
  8. 时区:名称或偏移编号
  9. mode: debug, epoch, verbose epoch or verbose
  10. 模式:调试、历元、详细历元或详细历元

the output in not debug mode is random number according to optional specifications.

非调试模式下的输出是根据可选规范的随机数。

tested with PHP 7.x

测试PHP 7. x

#11


-2  

$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);

Full random date and time

完全随机的日期和时间

#1


78  

PHP has the rand() function:

PHP具有rand()函数:

$int= rand(1262055681,1262055681);

It also has mt_rand(), which is generally purported to have better randomness in the results:

它还具有mt_rand(),一般认为其结果具有更好的随机性:

$int= mt_rand(1262055681,1262055681);

To turn a timestamp into a string, you can use date(), ie:

要将时间戳转换为字符串,可以使用date(),即:

$string = date("Y-m-d H:i:s",$int);

#2


34  

If given dates are in date time format then use this easiest way of doing this is to convert both numbers to timestamps, then set these as the minimum and maximum bounds on a random number generator.

如果给定的日期是日期时间格式,那么使用最简单的方法是将两个数字转换为时间戳,然后将它们设置为随机数生成器的最小和最大边界。

A quick PHP example would be:

一个简单的PHP示例是:

// Find a randomDate between $start_date and $end_date
function randomDate($start_date, $end_date)
{
    // Convert to timetamps
    $min = strtotime($start_date);
    $max = strtotime($end_date);

    // Generate random number using above bounds
    $val = rand($min, $max);

    // Convert back to desired date format
    return date('Y-m-d H:i:s', $val);
}

This function makes use of strtotime() as suggested by zombat to convert a datetime description into a Unix timestamp, and date() to make a valid date out of the random timestamp which has been generated.

该函数使用zombat建议的strtotime()将时间描述转换为Unix时间戳,并使用date()从生成的随机时间戳中获得有效的日期。

#3


24  

You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.

你可以用一个随机数来确定一个随机的日期。获取日期之间的0到天数之间的随机数。然后在第一次约会的时候加上这个数字。

For example, to get a date a random numbers days between now and 30 days out.

例如,为了得到一个日期,从现在到30天的随机数字。

echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));

#4


8  

Here's another example:

这是另一个例子:

$datestart = strtotime('2009-12-10');//you can change it to your timestamp;
$dateend = strtotime('2009-12-31');//you can change it to your timestamp;

$daystep = 86400;

$datebetween = abs(($dateend - $datestart) / $daystep);

$randomday = rand(0, $datebetween);

echo "\$randomday: $randomday\n";

echo date("Y-m-d", $datestart + ($randomday * $daystep)) . "\n";

#5


7  

Another solution using PHP DateTime

另一个使用PHP DateTime的解决方案。

$start and $end are DateTime objects and we convert into Timestamp. Then we use mt_rand method to get a random Timestamp between them. Finally we recreate a DateTime object.

$start和$end是DateTime对象,我们将其转换为Timestamp。然后我们使用mt_rand方法来获取它们之间的随机时间戳。最后,我们重新创建一个DateTime对象。

function randomDateInRange(DateTime $start, DateTime $end) {
    $randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
    $randomDate = new DateTime();
    $randomDate->setTimestamp($randomTimestamp);
    return $randomDate;
}

#6


4  

The best way :

最好的方法:

$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );

#7


2  

The amount of strtotime in here is WAY too high.
For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:

这里的时间太长了。对于任何在1971年之前和2038年之后有兴趣的人来说,以下是一个现代、灵活的解决方案:

function random_date_in_range( $date1, $date2 ){
    if (!is_a($date1, 'DateTime')) {
        $date1 = new DateTime( (ctype_digit((string)$date1) ? '@' : '') . $date1);
        $date2 = new DateTime( (ctype_digit((string)$date2) ? '@' : '') . $date2);
    }
    $random_u = random_int($date1->format('U'), $date2->format('U'));
    $random_date = new DateTime();
    $random_date->setTimestamp($random_u);
    return $random_date->format('Y-m-d') .'<br>';
}

Call it any number of ways ...

可以用各种方式来称呼它……

// timestamps
echo random_date_in_range(157766400,1489686923);

// any date string
echo random_date_in_range('1492-01-01','2050-01-01');

// English textual parsing
echo random_date_in_range('last Sunday','now');

// DateTime object
$date1 = new DateTime('1000 years ago');
$date2 = new DateTime('now + 10 months');
echo random_date_in_range($date1, $date2);

As is, the function requires date1 <= date2.

因此,函数需要date1 <= date2。

#8


2  

By using carbon and php rand between two dates

在两个日期之间使用碳和php rand。

$startDate = Carbon::now();
$endDate   = Carbon::now()->subDays(7);

$randomDate = Carbon::createFromTimestamp(rand($endDate->timestamp, $startDate->timestamp))->format('Y-m-d');

OR

$randomDate = Carbon::now()->subDays(rand(0, 7))->format('Y-m-d');

#9


0  

Simplest of all, this small function works for me I wrote it in a helper class datetime as a static method

最简单的是,这个小函数适用于我,我将它作为一个静态方法写在一个helper类datetime中

/**
 * Return date between two dates
 *
 * @param String $startDate
 * @param String $endDate
 * @return String
 *
 * @author Kuldeep Dangi <kuldeepamy@gmail.com>
 */
public static function getRandomDateTime($startDate, $endDate)
{
    $randomTime = mt_rand(strtotime($startDate), strtotime($endDate));
    return date(self::DATETIME_FORMAT_MYSQL, $randomTime);

}

#10


-1  

Pretty good question; needed to generate some random sample data for an app.

很好的问题;需要为应用生成一些随机样本数据。

You could use the following function with optional arguments to generate random dates:

您可以使用以下函数和可选参数来生成随机日期:

function randomDate($startDate, $endDate, $format = "Y-M-d H:i:s", $timezone = "gmt", $mode = "debug")
{
    return $result;
}

sample input:

样例输入:

echo 'UTC: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", "utc") . '<br>';
//1942-Jan-19 07:00:00

echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '<br>'; 
//1942/Jan/19 00:00 AM

echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '<br>';
//1942 January

echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '<br>';
//20:00:00

echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '<br>';
//1942-Jan-19 02:00:00

echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '<br>';
//1942-Jan-19 00:00:00

readers requirements could vary from app to another, in general hope this function is a handy tool where you need to generate some random dates/ sample data for your application.

不同的应用程序对读者的要求也不尽相同,总的来说,希望这个功能是一个方便的工具,您需要为应用程序生成一些随机的日期/示例数据。

Please note that the function initially in debug mode, so change it to $mood="" other than debug in production .

请注意,该函数最初处于调试模式,因此将其更改为$mood="",而不是在生产中调试。

The function accepts:

函数接受:

  1. start date
  2. 开始日期
  3. end date
  4. 结束日期
  5. format: any php accepted format for date or time
  6. 格式:任何php接受的日期或时间格式
  7. timezone: name or offset number
  8. 时区:名称或偏移编号
  9. mode: debug, epoch, verbose epoch or verbose
  10. 模式:调试、历元、详细历元或详细历元

the output in not debug mode is random number according to optional specifications.

非调试模式下的输出是根据可选规范的随机数。

tested with PHP 7.x

测试PHP 7. x

#11


-2  

$yeni_tarih = date('Y-m-d', strtotime( '+'.mt_rand(-90,0).' days'))." ".date('H', strtotime( '+'.mt_rand(0,24).' hours')).":".rand(1,59).":".rand(1,59);

Full random date and time

完全随机的日期和时间