How to generate random date between two dates using php?

前端 未结 13 1906
甜味超标
甜味超标 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:20

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

提交回复
热议问题