In this tutorial, I will be showing you how to create a random date in PHP. This sort of thing is useful for debugging or for auto-generating a list of dates.
There are two ways to do this:
- Generate a random unix timestamp.
- Generate a random date string.
Generating a random timestamp with PHP.
As you probably already know, a Unix timestamp can only be used for dates that are from the 1st of January 1970 or onward. i.e. If you need to generate a date that is pre-1970, then you should probably skip this section and scroll down to the next one:
<?php //Generate a timestamp using mt_rand. $timestamp = mt_rand(1, time()); //Format that timestamp into a readable date string. $randomDate = date("d M Y", $timestamp); //Print it out. echo $randomDate;
Quick explanation of the code snippet above:
- We generated a random timestamp using PHP’s mt_rand function. We set the function up to provide us with a random timestamp that falls between the 1st of January 1970 and our current time.
- We formatted that timestamp into a “d M Y” format.
- We printed out the result.
To generate timestamps that will include future dates, you can use the following:
<?php //Include future dates and past dates. $timestamp = mt_rand(1, 2147385600); //Etc.
Note that I used the timestamp “2147385600”, simply because this is the day before the Unix Time Stamp is expected to stop working properly (a 32-bit overflow is expected to occur).
To customise the “range”, simply set the min and max values of mt_rand to the timestamps that represent your date range. You could even do this:
<?php //Start point of our date range. $start = strtotime("10 September 2000"); //End point of our date range. $end = strtotime("22 July 2010"); //Custom range. $timestamp = mt_rand($start, $end); //Print it out. echo date("Y-m-d", $timestamp);
Generating a random date string in PHP.
The next example isn’t perfect, simply because a number of dates will be left out. However, it is pretty robust in terms of not being susceptible to timestamp issues:
<?php //Generate a random year using mt_rand. $year= mt_rand(1000, date("Y")); //Generate a random month. $month= mt_rand(1, 12); //Generate a random day. $day= mt_rand(1, 28); //Using the Y-M-D format. $randomDate = $year . "-" . $month . "-" . $day; //Echo. echo $randomDate;
As you can see, we left out the 29th, 30th and 31st, simply because not every month will contain those dates. If you want it to be “smarter”, then you could set up a SWITCH statement that chooses the maximum number of days based on the month that has been generated.