简体   繁体   中英

How to get next occurrence of day of the week at a certain hour in PHP?

I'm trying to start a mail chain for onboarding my users on my platform. I have an entity Onboarding with the following properties:

  • Onboarding::dayOfWeek (int)
  • Onboarding::hourOfDay (int)

So what I want is to be able to find the next occurrence of the couple (dayOfWeek, hourOfDay). For example next "Friday at 12:00:00" or next "Wednesday at 18:00:00". And then program one e-mail per week for a given number of weeks. The problem is in finding the nearest scheduled time (the rest is pretty straightforward).

I have come up with this code using some other answers on stackoverflow:

$date = new DateTime();
$date->setISODate($date->format('o'), $date->format('W'), $dayOfWeek);
$date->setTime($hourOfday, 0);

if ($date < new DateTime()) {
    $date->modify('+1 week');
}

This works exactly as expected but feels "hacky", is there a proper way of doing this ? Ideally something like this should work:

$days = [1 => 'Monday', 2 => 'Tuesday', 3 => 'Wednesday']; // and so on
$date = new \DateTime("next {$days[$dayOfWeek]} ${hourOfday}:00:00");

BUT at the time of this writing it is Friday and any hour of friday is next week's Friday. I would expect that if I am looking for a hourOfDay after my current time, it would be set for today ! Did I miss something out ? Because this would make me manually check if the date is more than a week from now and then ->modify('-1 week') and so we're back to the previous script.

You could use the DateTime format options to do this: https://secure.php.net/manual/en/book.datetime.php/en/class.datetime.php

$eventDate = DateTime::createFromFormat('m/d/y h:i', '02/26/11 08:00', new DateTimeZone('Europe/Madrid'));
$eventDate->modify('-1 week');
echo date_format($eventDate, 'm/d/Y (l) - H:m:s');

You can test it here http://phpfiddle.org/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM