I have created a function that works fine with 32-bit dates (acceptable with strtotime), but it is scalable is not. I need to generate random birth dates, so I have to use it to generate dated (and only & lt; = 5.2.13, to make it even more difficult) tasks.
Here's what I have: public static work random date ($ start_date, $ end_date, $ format = dateTimeHelper :: DATE_FORMAT_SQL_DATE) {if ($ start_date instanceof DateTime) $ start_date = $ start_date- & gt; Format (DateTimeHelper :: DATE_FORMAT_YMDHMS); If ($ end_date example of dateTime) $ end_date = $ end_date- & gt; Format (DateTime: :: DATE_FORMAT_YMDHMS); // convert timeramps to milliseconds $ min = striatime ($ start_date); $ Max = strontime ($ end_date); // Generate a random number using the above limits $ val = rand ($ min, $ max); // Convert back to the desired date format return date ($ format, $ val); }
Now, how can I generate a random date between two dateTimes?
Thank you!
edit: Fixed bugs according to comments.
Suppose you have a description of the start and end dates, tell what is getdate, you can generate timelines without any date:
< Code> $ year = rand ($ start_details ['year'], $ end_details ['year']); $ Isleap = $ year = 400 == 0 || ($ Years% 100! = 0 & $ years% 4); $ Min_yday = $ Years & gt; $ 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 did not test). The code above considers UTC, you may want to offset according to your time zone.
Comments
Post a Comment