Scroll through dates by printing a field for each

Asked

Viewed 1,246 times

3

I’m making a system kind of like a calendar / schedule. In it I have a table semestre who has a field data de incio and one of data fim and I need to go through these dates by printing the name of each day on head of a table and a button for each of these days so that the user can register or not a new entry on that day.

How to go these days? I’ve tried foreach but it didn’t work, I also tried a logic with a for and I couldn’t...

Follow some of the code I’ve made so far:

if(!isset($_SESSION)) {
   session_start();
} 

$idSemestre = $_SESSION['SemestreGeral'];

$oSemestre = new semestresclass();
$oSemestre -> listarEdicao($idSemestre);  

$array = mysql_fetch_array($oSemestre->retorno());

$start_date = $array['DataDeInicio'];
$end_date = $array['DataDeTermino'];

$dataInicio = strtotime($start_date);
$dataFim = strtotime($end_date);

foreach ?????????????????????

2 answers

3

Create an object of the type \DatePeriod passing as parameters the initial and final date, in addition to a \DateInterval of type "P1D", that is to say a one-day period between the dates.

Your code would look like this:

$dataInicio = new \DateTime(strtotime($start_date));
$dataFim    = new \DateTime(strtotime($end_date));
$periodo    = new \DatePeriod($dataInicio, new \DateInterval("P1D"), $dataFim);

foreach ($periodo as $data) {
    echo $data->format('d/m/Y');
}

3


From php5.3 there is the class Dateperiod or allows manipulation between periods of dates. Simply inform the date of beginning, end and the period that will be modified in the case P1D(one day) Other values available are:

Y   Anos
M   Meses
D   Dias
W   Semanas
H   Horas
M   Minutos
S   Segundos

Example

<?php

$inicio = new DateTime('2014-10-26');
$fim = new DateTime('2014-10-31');
$fim->modify('+1 day');

$interval = new DateInterval('P1D');
$periodo = new DatePeriod($inicio, $interval ,$fim);

foreach($periodo as $data){
    echo $data->format("l") . ' | '.$data->format("d/m/Y"). '<br>';

}
  • Very feral, that was it guys!!! Now you see, I needed to limit these days to appear one week and then jump to another... Would any of you have an idea how to do that?

  • 2

    @Alceu as well? If it is the case, create a question specifically for this case :)

Browser other questions tagged

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