How to generate random date between two dates using php?

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

    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") . '
    '; //1942-Jan-19 07:00:00 echo 'GMT: ' . randomDate("1942-01-19", "2016-06-03", "Y/M/d H:i A", "gmt") . '
    '; //1942/Jan/19 00:00 AM echo 'France: ' . randomDate("1942-01-19", "2016-06-03", "Y F", "Europe/Paris") . '
    '; //1942 January echo 'UTC - 4 offset time only: ' . randomDate("1942-01-19", "2016-06-03", "H:i:s", -4) . '
    '; //20:00:00 echo 'GMT +2 offset: ' . randomDate("1942-01-19", "2016-06-03", "Y-M-d H:i:s", 2) . '
    '; //1942-Jan-19 02:00:00 echo 'No Options: ' . randomDate("1942-01-19", "2016-06-03") . '
    '; //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

提交回复
热议问题