How to Create a Random Date in PHP

While browsing some forums the other day, I came across this question – “How do I find a random date in PHP?”

This is a pretty simple operation, if we make use of a few built-in PHP functions – time(), strtotime(), and date(). In this article, we’ll see how these three can work together to find a random date within a given range.

The PHP time() Function and Timestamps

The PHP time() function is very simple. It returns the current time.

It helps us understand something else though – Unix timestamps. The time() function, along with all of PHP’s time/date functions, deals with Unix timestamps. This is an integer which represents the number of seconds that have elapsed since Jan 1, 1970 (considered the beginning of the “Unix epoch”).

For example, the current timestamp for Thursday, Feb. 7 9:57 PM is 1202439456. You can do the math if you want. I’ll trust PHP.

This allows us to do a lot of simple operations with time, however. We know that a timestamp deals with seconds – so we can add/subtract a certain number of seconds to modify the time by minutes, hours, or days.

$time = time();  //  Current time
$time = time() - 60;  //  One minute ago
$time = time() + 120;  //  Two minutes in the future
$time = time() - 3600;  //  One hour ago
PHP’s date() Function – Formatted Dates

The time() function and timestamps become really powerful when you understand how to use the date() function.

This takes two parameters – a date format string and a timestamp. It then takes the timestamp and outputs the given time in the given format. You can find a list of date format characters at php.net. Here are a few examples, though…

$now = time();
 
$x = date("m-d-Y", $now);  //  02-07-2008
$y = date("M d Y", $now);  // Feb 07 2008
$z = date("F d, Y", $now);  // February 07, 2008

Notice that the letters (mMFdY) represent the actual dates, while the spacing and punctuation is just used for formatting.

Getting Custom Timestamps with strtotime()

The last function to look at is strtotime(). This takes a formatted date string (like “Feb 07 2008″ or “1 day ago”) and returns the appropriate Unix timestamp.

This allows you to fetch a timestamp for pretty much any date you want and then manipulate it in other ways – using the date() function or your own mathematical functions.

This is also going to help us find a random date in between two given dates.

Finding a Random Date

In order to find a random date, we need three things. The rand() function – to get a random number or timestamp. A start date. An end date.

In this simple example, we’ll find a random time between the start of the Unix epoch (timestamp = 0) and the current time. Then we’ll format it in the m-d-Y format for easy readability.

$time = rand( 0, time() );
echo date("m-d-Y", $time);

Run that, and you’ll find a random date between “Jan 1 1970″ and whatever your current date is – “Feb 7 2008″ for me.

We can make this a little better by using strtotime to set the min and max value for rand(). In this example, we’ll find a date in 2007 – between “Jan 01 2007″ and “Dec 31 2007″.

$time = rand( strtotime("Jan 01 2007"), strtotime("Dec 31 2007") );
echo date("m-d-Y", $time);

And there you go. Replace the strtotime() calls that I used, and you can find a random date within any given daterange.

However, take note that there are limitations to the extent of the Unix timestamp. By using a negative number, the earliest date you can get with date() is around 1901. The latest date you’ll be able to work with is around 2025. This is a limitation based on the size of integers in PHP – the Unix timestamp just can’t get any bigger in its basic form.

Bookmark and Share:
  • Digg
  • Furl
  • del.icio.us
  • StumbleUpon
  • MisterWong
  • DZone
  • Technorati

Tags: , , ,

14 Comments to “How to Create a Random Date in PHP”

  1. Comment créer une date aléatoire en PHP said this on

    [...]  How to Create a Random Date in PHP (0 visite) [...]

  2. tresloukadu said this on

    thanks!! it worked very awesome here!

  3. How to Find a Random Date in PHP - Tutorial Collection said this on

    [...] View Tutorial No Comment var addthis_pub=”izwan00″; BOOKMARK This entry was posted on Friday, June 5th, 2009 at 8:04 am and is filed under Php Tutorials. You can follow any responses to this entry through the RSS 2.0 feed. You can leave a response, or trackback from your own site. [...]

  4. FFXIV guide said this on

    There is no god… atleast that”s how i feel after reading this

  5. Tera Laufer said this on

    You have such a great blog! I’m glad I found it. .
    Regards
    Al Khafji

  6. Hosea Mutart said this on

    Excellent details concerning SEO. Thank you for a excellent submit. I had realized most new info regarding onpage.

  7. Jonelle Traum said this on

    I know this if off topic but I’m looking into starting my own blog and was wondering what all is needed to get setup? I’m assuming having a blog like yours would cost a pretty penny? I’m not very web smart so I’m not 100% positive. Any suggestions or advice would be greatly appreciated. Appreciate it

  8. Golf training program said this on

    Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog? My blog site is in the exact same area of interest as yours and my visitors would genuinely benefit from some of the information you provide here. Please let me know if this okay with you. Appreciate it!

  9. Jean Ross said this on

    Very useful post.

  10. events planner said this on

    [...]The information mentioned in the article are some of the best available [...]……

    [...]below you’ll find the link to some sites that we think you should visit[...]……

  11. The Knowledge of London said this on

    Excellent random date tutorial, looks like I should get into php more. Thanks

  12. squirrel proof birdfeeders said this on

    far east square japanese restaurant…

    [...]floods are expected more frequently with climate change – so[...]…

  13. vnc vps said this on

    of course like your web-site however you have to test the spelling on several of your posts. Many of them are rife with spelling issues and I find it very bothersome to inform the truth on the other hand I will certainly come again again.

  14. Victorino Noval Foundation said this on

    modern politics questions…

    [...]health officials concluded in 2004 that more than three-quarters of[...]…

Leave a Reply