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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1972712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 04:30:31  来源:igfitidea点击:

How to generate random date between two dates using php?

phpdatedatetimetimestamp

提问by M.E

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);

回答by zombat

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);

回答by Somnath Muluk

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() 从已生成的随机时间戳中生成有效日期。

回答by Sam

Another solution using PHP DateTime

使用 PHP 的另一种解决方案 DateTime

$startand $endare DateTimeobjects and we convert into Timestamp. Then we use mt_randmethod to get a random Timestamp between them. Finally we recreate a DateTimeobject.

$start$endDateTime对象,我们转换为时间戳。然后我们使用mt_rand方法在它们之间获取随机时间戳。最后我们重新创建一个DateTime对象。

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

回答by Brent Baisley

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'));

回答by ariefbayu

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";

回答by Максим С

The best way :

最好的方法 :

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

回答by vijaykumar

By using carbonand php randbetween two dates

通过在两个日期之间使用carbon和 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');

回答by neokio

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

这里的数量strtotime太高了。
对于兴趣跨越 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

回答by Sébastien Gicquel

An other solution where we can use date_format :

我们可以使用 date_format 的另一个解决方案:

 /**
 * Method to generate random date between two dates
 * @param $sStartDate
 * @param $sEndDate
 * @param string $sFormat
 * @return bool|string
 */

function randomDate($sStartDate, $sEndDate, $sFormat = 'Y-m-d H:i:s') {
    // Convert the supplied date to timestamp
    $fMin = strtotime($sStartDate);
    $fMax = strtotime($sEndDate);
    // Generate a random number from the start and end dates
    $fVal = mt_rand($fMin, $fMax);
    // Convert back to the specified date format
    return date($sFormat, $fVal);
}

Source : https://gist.github.com/samcrosoft/6550473

来源:https: //gist.github.com/samcrosoft/6550473

You could use for example :

例如,您可以使用:

$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');

回答by Manojkiran.A

i had a same situation before and none of the above answers fix my problem so i

我之前也遇到过同样的情况,以上答案都没有解决我的问题,所以我

Came with new function

自带新功能

function randomDate($startDate, $endDate, $count = 1 ,$dateFormat = 'Y-m-d H:i:s')
{
   //inspired by
    // https://gist.github.com/samcrosoft/6550473

    // Convert the supplied date to timestamp
    $minDateString = strtotime($startDate);
    $maxDateString = strtotime($endDate);

    if ($minDateString > $maxDateString) 
    {
        throw new Exception("From Date must be lesser than to date", 1);

    }

    for ($ctrlVarb = 1; $ctrlVarb <= $count; $ctrlVarb++) 
    { 
       $randomDate[] = mt_rand($minDateString, $maxDateString); 
    }
    if (sizeof($randomDate) == 1) 
    {
        $randomDate = date($dateFormat, $randomDate[0]);
        return $randomDate;
    }elseif (sizeof($randomDate) > 1) 
    {
        foreach ($randomDate as $randomDateKey => $randomDateValue) 
        {
           $randomDatearray[] =  date($dateFormat, $randomDateValue);
        }
        //return $randomDatearray;
        return array_values(array_unique($randomDatearray));
    }
}

Now the testing Part(Data may change while testing )

现在测试部分(测试时数据可能会改变)

$fromDate = '2012-04-02';
$toDate = '2018-07-02';

print_r(randomDate($fromDate,$toDate,1));

print_r(randomDate($fromDate,$toDate,1));

result will be

结果将是

2016-01-25 11:43:22

print_r(randomDate($fromDate,$toDate,1));

print_r(randomDate($fromDate,$toDate,1));

array:10 [▼
  0 => "2015-08-24 18:38:26"
  1 => "2018-01-13 21:12:59"
  2 => "2018-06-22 00:18:40"
  3 => "2016-09-14 02:38:04"
  4 => "2016-03-29 17:51:30"
  5 => "2018-03-30 07:28:48"
  6 => "2018-06-13 17:57:47"
  7 => "2017-09-24 16:00:40"
  8 => "2016-12-29 17:32:33"
  9 => "2013-09-05 02:56:14"
]

But after the few tests i was thinking about what if the inputs be like

但是在几次测试之后,我在想如果输入像什么

$fromDate ='2018-07-02 09:20:39';
$toDate = '2018-07-02 10:20:39';

So the duplicates may occur while generating the large number of dates such as 10,000

因此在生成大量日期时可能会发生重复,例如 10,000

so i have added array_uniqueand this will return only the non duplicates

所以我添加了array_unique,这将只返回非重复项