How to generate random date between two dates using php?

前端 未结 13 1899
甜味超标
甜味超标 2020-11-27 15:55

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 a

13条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-27 16:28

    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

提交回复
热议问题