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

I made a function that works fine with 32-bit dates (valid with strtotime), but it does not scale. I need to randomly generate birth dates for people, so I have to use DateTime functions (and only <= 5.2.13 to make it even more difficult) to create 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 number using above bounds $val = rand($min, $max); // Convert back to desired date format return date($format, $val); } 

So how can I create a random date between two DateTimes?

thanks!

+4
source share
1 answer

Edit: fixed bugs according to comments.

Suppose you have information about start and end dates, let's say the same as getdate () returns, then you can generate the date without having to go through the 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 this (I have not tested). The code above assumes UTC, you may need an offset according to your time zone .5

+1
source

Source: https://habr.com/ru/post/1316204/


All Articles