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 answer for Java not php
for example :
$string = randomdate(1262055681,1262055681);
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 answer for Java not php
for example :
$string = randomdate(1262055681,1262055681);
Another solution using PHP
DateTime
$start
and$end
areDateTime
objects and we convert into Timestamp. Then we usemt_rand
method to get a random Timestamp between them. Finally we recreate aDateTime
object.You can just use a random number to determine a random date. Get a random number between 0 and number of days between the dates. Then just add that number to the first date.
For example, to get a date a random numbers days between now and 30 days out.
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:
sample input:
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:
the output in not debug mode is random number according to optional specifications.
tested with PHP 7.x
i had a same situation before and none of the above answers fix my problem so i
Came with new function
Now the testing Part(Data may change while testing )
print_r(randomDate($fromDate,$toDate,1));
result will be
print_r(randomDate($fromDate,$toDate,1));
But after the few tests i was thinking about what if the inputs be like
So the duplicates may occur while generating the large number of dates such as
10,000
so i have added
array_unique
and this will return only the non duplicatesThe amount of
strtotime
in here is WAY too high.For anyone whose interests span before 1971 and after 2038, here's a modern, flexible solution:
Call it any number of ways ...
As is, the function requires
date1
<=date2
.Simplest of all, this small function works for me I wrote it in a helper class
datetime
as a static method