开发者

PHP: How can I make a randomDate($startDate, $endDate) function?

i have made a function which works just fine with 32-bit dates (acceptable with strtotime), but that is not scalable. i need to randomly generate peoples dates of birth, so i must use DateTime (and only <=5.2.13, to make it even more difficult) functions to generate them.

here is what i had:

public static function randomDate($start_date, $end_date, $format = DateTimeHelper::DATE_FORMAT_SQL_DATE)
{
    if($start_date instanceof DateTime)     $start_date = $start_date->format(DateTimeHelper::DATE_FORMAT_YMDHMS);
    if($end_date instanceof DateTime)       $end_date   = $end_date->format(DateTimeHelper::DATE_FORMAT_YMDHMS);

    // Convert timetamps to millis
    $min = strtotime($start_date);
    $max = strtotime($end_date);

    // Generate random n开发者_StackOverflow社区umber using above bounds
    $val = rand($min, $max);

    // Convert back to desired date format
    return date($format, $val);
}

so now, how can i generate a random date between two DateTimes?

thanks!


Edit: fixed bugs as per comments.

Suppose you have the details on start and end dates, lets say as in what is returned by getdate(), then you can generate a date without having to go through a timestamp:

$year = rand($start_details['year'], $end_details['year']);

$isleap = $year % 400 == 0 || ($year % 100 != 0 && $year % 4);
$min_yday = $year > $start_details['year'] ? 0 : $start_details['yday'];
$max_yday = $year == $end_details['year'] ? $end_details['yday'] : ($isleap ? 365 : 364);

$yday = rand($min_yday, $max_yday);

$sec_in_day = 24 * 60 * 60;

$date_details = getdate($yday * $sec_in_day + ($isleap ? 2 * 365 * $sec_in_day : 0));
return sprintf('%04d-%02d-%02d', $year, $date_details['mon'], $date_details['mday']);

Something like that (I didn't test). The code above assumes UTC, you might want to offset according to your time zone.5

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜