Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

php - Generate random dates with random times between two dates for selected period and frequency

I have to create a scheduling component that will plan e-mails that need to be sent out. Users can select a start time, end time, and frequency. Code should produce a random moment for every frequency, between start and end time. Outside of office hours.

Paramaters:

User can select a period between 01/01/2020 (the start) and 01/01/2021 (the end). In this case user selects a timespan of one exactly year.

User can select a frequency. In this case user selects '2 months'.

Function:

Code produces a list of datetimes. The total time (one year) is divided by frequency (2 months). We expect a list of 6 datetimes.

Every datetime is a random moment in said frequency (2 months). Within office hours.

Result:

An example result for these paramaters might as follows, with the calculated frequency bounds for clarity:

  • [jan/feb] 21-02-2020 11.36
  • [mrt/apr] 04-03-2020 16.11
  • [mei/jun] 13-05-2020 09.49
  • [jul-aug] 14-07-2020 15.25
  • [sep-okt] 02-09-2020 14.09
  • [nov-dec] 25-12-2020 13.55

--

I've been thinking about how to implement this best, but I can't figure out an elegant solution.

How could one do this using PHP?

Any insights, references, or code spikes would be greatly appreciated. I'm really stuck on this one.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you're just asking for suggestions on how to generate a list of repeating (2 weekly) dates with a random time between say 9am and 5pm? Is that right?

If so - something like this (untested, pseudo code) might be a starting point:

$start    = new Datetime('1st January 2021');
$end      = new Datetime('1st July 2021');
$day_start = 9;
$day_end = 17;

$date = $start;
$dates = [$date]; // Start date into array
while($date < $end) {
            
    $new_date = clone($date->modify("+ 2 weeks"));
    $new_date->setTime(mt_rand($day_start, $day_end), mt_rand(0, 59));
        
    $dates[] = $new_date;
}

var_dump($dates);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...