Skip to content

Instantly share code, notes, and snippets.

@gpedro
Created June 29, 2015 19:13
Show Gist options
  • Save gpedro/d974a944dab044c70955 to your computer and use it in GitHub Desktop.
Save gpedro/d974a944dab044c70955 to your computer and use it in GitHub Desktop.
Algoritmo em PHP que pega o início e fim da semana em um intervalo de data
<?php
function toDateString(DateTime $date) {
return $date->format("d-m-Y");
}
class Semana {
private $inicio;
private $fim;
public function getInicio() {
return $this->inicio;
}
public function setInicio($value) {
$this->inicio = $value;
}
public function getFim() {
return $this->fim;
}
public function setFim($value) {
$this->fim = $value;
}
public function done() {
return $this->fim && $this->inicio;
}
public function __toString() {
return $this->getInicio() . " - " . $this->getFim();
}
}
// 28/03/2015 até 05/08/2016
$dateInicial = new DateTime("2015-03-01 00:00:00");
$dateFinal = new DateTime("2015-05-01 23:59:59");
if ($dateInicial > $dateFinal) {
throw new Exception("DateInicial deve ser menor que a DataFinal");
}
$diasIntervaloDiff = $dateInicial->diff($dateFinal);
$diasIntervalo = intval($diasIntervaloDiff->format('%a'));
$semanas = array();
$dateAtual = $dateInicial;
$done = false;
while($done == false) {
$diaSemana = $dateAtual->format('w');
$semana = new Semana();
$semana->setInicio(toDateString($dateAtual));
if ($diaSemana == 1) {
$dateAtual->modify("+6 days");
} else {
$pulaDias = 8 - $diaSemana;
$dateAtual->modify("+" . $pulaDias . " days");
}
if ($dateAtual >= $dateFinal) {
$semana->setFim(toDateString($dateFinal));
$done = true;
} else {
$semana->setFim(toDateString($dateAtual));
}
array_push($semanas, $semana);
}
var_dump($semanas);
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment