user939659
user939659

Reputation: 33

How can I generate a random date in the past?

using PHP.

It has to be a valid one, like:

2001-6-28 14:20:29

?

(and if possible not older than 10 years)

Upvotes: 3

Views: 498

Answers (3)

Thomas Winsnes
Thomas Winsnes

Reputation: 1961

unix timestamp is an integer from 0 to n so you can just use the normal random method in php :)

$timestamp = rand(0, time() - 60*60*24*365*10);

// Prints something like: Monday 8th of August 2005 03:12:46 PM
echo date('l jS \of F Y h:i:s A', $timestamp);

Upvotes: 5

Evert
Evert

Reputation: 99523

$date = mt_rand(strtotime('-10 years'), time());

This will get you a unix timestamp, use date() to reformat it; and next time do the research yourself as this is a most basic question.

Upvotes: 4

Ed Heal
Ed Heal

Reputation: 59997

Get the seconds since the epoch for the two dates in question. Generate a random number between that range. Then convert back into a date.

Upvotes: 4

Related Questions