Return days of the year, removing those that are in a Variable

Asked

Viewed 28 times

1

I need a PHP function that returns me every day of the year except those that were previously selected.

Example My client selected ( 01/01,02/01,04/01,12/01,12/05,18/01,08/01,10/11,05/12,11/09,01/12 )

Then I need you to manage all the remaining days to be recorded at the bank.

It can be in American format.

The list above is just a small example, as it can be marked up to 250 days, thus remaining a few days

1 answer

2


You can solve this problem with the following steps, generate a date range (the calendar of the year itself) with the help of the classes DateInterval and DatePeriod defining the increment unit (PD1) of the range.

Then take the current day of the foreach and compare with the list of exceptions and do that in_array() skip them, this will generate the SQL string with multiple values to run only an Insert at the end.

IS important comment that the date range does not include the final date in case 31/12/2018 so the line: $dataFim->modify('+1 day');. modify() adds one more day to the date it turns 01/01/2019.

$dataInicio = new DateTime('2018-01-01');
$dataFim = new DateTime('2018-12-31');
$dataFim->modify('+1 day');
$intervalo = new DateInterval('P1D');

$diasAno = new DatePeriod($dataInicio, $intervalo, $dataFim);

$selecionados = '01/01,02/01,04/01,12/01';
$excecoes = explode(',', $selecionados);


foreach($diasAno as $date){
    if(!in_array($date->format('d/m'), $excecoes)){
        $sql .= sprintf("('%s'),", $date->format('Y-m-d'));
    }
}

$sql = rtrim($sql, ',');
echo $sql;

The exit is something like:

('2018-01-01'),('2018-01-02'),('2018-01-03'),('2018-01-04')

Browser other questions tagged

You are not signed in. Login or sign up in order to post.