How to get the correct date for the next event

0

I have a list with the days of the week that shows when an event should occur and another variable with the interval that this event should occur, for example, if the list is 0,1,0,1,0,1,0 [seg-qua-sex] will events occur, and if in that my interval variable I have the value of 2 it means that it should occur week yes week not.

What I need is to know when the next event will occur, does anyone have any idea how I can do this, my problem is much more complex, but I tried to leave it as simple as possible but I'm getting caught up in that part. p>     

asked by anonymous 23.02.2016 / 02:50

2 answers

1

In a procedural way, with only the question information:

$intervalo = 2; //2 em 2 semanas
$semanaAtual = array(0,0,1,0,0,0,0); //domingo, segunda, terça, quarta, quinta, sexta, sábado
$semanaProxima = array(0,0,0,1,0,0,0); //domingo, segunda, terça, quarta, quinta, sexta, sábado

$ultimoEvento = '2016-02-23'; //string contendo a data do último evento
$diaDaSemana = date("w", strtotime($ultimoEvento)); //dia da semana em que ocorreu o último evento
$dataProximoEvento = ''; //data do próximo evento

//verifica se dentro da própria semana ainda ocorrerá o evento
for($i=$diaDaSemana+1; $i<=6; $i++) {
    if($semanaAtual[$i]) {
        $dataProximoEvento = date("Y-m-d", strtotime($ultimoEvento . ' + ' . ($i-$diaDaSemana) . ' days'));
        break;
    }
}

//verifica qual o próximo dia do evento na próxima semana de acordo com o intervalo
if(empty($dataProximoEvento)) {
    $primeiroDiaSemana = new DateTime(date('Y-m-d', strtotime("last Sunday", strtotime($ultimoEvento . ' + ' . (7*$intervalo) . ' days') )));

    for($i=0; $i<=6; $i++) {
        if($semanaProxima[$i]) {
            $dataProximoEvento = date('Y-m-d', strtotime($primeiroDiaSemana->modify("+$i days")->format("Y-m-d H:i")));
            break;
        }
    }
}

echo $dataProximoEvento;
    
23.02.2016 / 12:45
0

I was able to solve the problem as follows

<?php
$regra_frequencia = '0,1,0,1,0,1,0'; 
$dow = explode(",", $regra_frequencia);
$dow_now = date('w');
$dow_repeat = array();
$intervalo = 2;

foreach($dow as $w => $on) {    
    if($on == 1) {
        $dow_repeat[] = $w;
    }
}

$dow_get = $dow_repeat[0];

if($dow_now < 6) {  
    foreach($dow_repeat as $d) {
        if($d > $dow_now) {
            $dow_get = $d;
            break;          
        }       
    }
}

$date = new DateTime(date('Y-m-d'));

if($dow_get > $dow_now) {
    $diff = $dow_get - $dow_now;
    $date->add(new DateInterval("P" . $diff . "D"));
    $dt_next_event = $date->format('Y-m-d');
} else {
    $diff = $dow_now - $dow_get;
    $date->sub(new DateInterval("P" . $diff . "D"));
    $date->add(new DateInterval("P" . $intervalo . "W"));
    $dt_next_event = $date->format('Y-m-d');    
}

echo $dt_next_event;
    
23.02.2016 / 12:46