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条回答
疯言疯语
2楼-- · 2020-01-24 21:29

The best way :

$timestamp = rand( strtotime("Jan 01 2015"), strtotime("Nov 01 2016") );
$random_Date = date("d.m.Y", $timestamp );
查看更多
唯我独甜
3楼-- · 2020-01-24 21:31

By using carbon and php rand between two dates

$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');
查看更多
\"骚年 ilove
4楼-- · 2020-01-24 21:32

PHP has the rand() function:

$int= rand(1262055681,1262055681);

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

$int= mt_rand(1262055681,1262055681);

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

$string = date("Y-m-d H:i:s",$int);
查看更多
forever°为你锁心
5楼-- · 2020-01-24 21:32

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:

// 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.

查看更多
够拽才男人
6楼-- · 2020-01-24 21:33

An other solution where we can use 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

You could use for example :

$date_random = randomDate('2018-07-09 00:00:00','2018-08-27 00:00:00');
查看更多
你好瞎i
7楼-- · 2020-01-24 21:37
$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

查看更多
登录 后发表回答