How to generate random date between two dates using php?

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

    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.

    0 讨论(0)
提交回复
热议问题