note 92561 added to function.rand
| From: | HugoScotthrmscott at hotmail dot com | Date: | Wed, 29 Jul 2009 14:52:09 +0000 |
| Subject: | note 92561 added to function.rand | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-158878@lists.php.net to get a copy of this message | ||
Here's a simple function to generate a random date between a start date and an end date.
It is inclusive of BOTH dates - so using dates 2009-04-01 and 2009-04-03 would generate a random
date that could be 2009-04-01, 2009-04-02 or 2009-04-03.
It won't work if the end date is prior to the start date and if you use a non-existant date (eg
2009-02-30) it defaults to 1970-01-01
the longer version:
<?php
function makeRandomDateInclusive($startDate,$endDate){
$days = round((strtotime($endDate) - strtotime($startDate)) / (60 * 60 * 24));
$n = rand(0,$days);
return date("Y-m-d",strtotime("$startDate + $n days"));
}
?>
and the one-line version for compactness freaks:
<?php
function makeRandomDateInclusive($startDate,$endDate){
return date("Y-m-d",strtotime("$startDate + ".rand(0,round((strtotime($endDate)
- strtotime($startDate)) / (60 * 60 * 24)))." days"));
}
?>
it is called like this
<?php
echo makeRandomDateInclusive('2009-04-01','2009-04-03');
?>
Hope this is of some use to someone
----
Server IP: 64.71.164.2
Probable Submitter: 78.114.12.99
----
Manual Page -- http://www.php.net/manual/en/function.rand.php
Edit -- https://master.php.net/note/edit/92561
Del: integrated -- https://master.php.net/note/delete/92561/integrated
Del: useless -- https://master.php.net/note/delete/92561/useless
Del: bad code -- https://master.php.net/note/delete/92561/bad+code
Del: spam -- https://master.php.net/note/delete/92561/spam
Del: non-english -- https://master.php.net/note/delete/92561/non-english
Del: in docs -- https://master.php.net/note/delete/92561/in+docs
Del: other reasons-- https://master.php.net/note/delete/92561
Reject -- https://master.php.net/note/reject/92561
Search -- https://master.php.net/manage/user-notes.php