How to generate random date between two dates usin

2020-01-24 21:09发布

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

for example :

$string = randomdate(1262055681,1262055681);

13条回答
Juvenile、少年°
2楼-- · 2020-01-24 21:20

Another solution using 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.

function randomDateInRange(DateTime $start, DateTime $end) {
    $randomTimestamp = mt_rand($start->getTimestamp(), $end->getTimestamp());
    $randomDate = new DateTime();
    $randomDate->setTimestamp($randomTimestamp);
    return $randomDate;
}
查看更多
太酷不给撩
3楼-- · 2020-01-24 21:22

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.

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

echo date('Y-m-d', strtotime( '+'.mt_rand(0,30).' days'));
查看更多
再贱就再见
4楼-- · 2020-01-24 21:23

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 .

The function accepts:

  1. start date
  2. end date
  3. format: any php accepted format for date or time
  4. timezone: name or offset number
  5. mode: debug, epoch, verbose epoch or verbose

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

tested with PHP 7.x

查看更多
兄弟一词,经得起流年.
5楼-- · 2020-01-24 21:26

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

result will be

2016-01-25 11:43:22

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

so i have added array_unique and this will return only the non duplicates

查看更多
SAY GOODBYE
6楼-- · 2020-01-24 21:28

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:

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.

查看更多
地球回转人心会变
7楼-- · 2020-01-24 21:28

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

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

}
查看更多
登录 后发表回答