Know what day falls next Monday

Asked

Viewed 1,413 times

4

I need a schedule for an agenda that gives me the date of next Monday from a certain date

Ex: today and day 01/06 I need to know what day the next 10 Mondays will fall.

1 = 05/06/2017
2 = 12/06/2017
3 = 19/06/2017
4 = 26/06/2017
5 = 03/07/2017
6 = 10/07/2017
8 = 17/07/2017
9 = 24/07/2017
10= 31/07/2017

My problem is knowing the next second from a certain date, because the next ones will be easier and only add up the 7 days

  • You can also use the same logic as this question

  • You could better title to "Algorithm to find out next second" ?

4 answers

6


Follow the example code for next Monday from a date:

$dia = new DateTime( '2017-06-01' );
$dia->modify( 'next monday' );

echo $dia->format('d/m/Y'); // 05/06/2017

Link to view the test

Catch the next 10 seconds in an array from the next second by picking up as reference the current day:

$dia = new DateTime();
$dia->modify( 'next monday' );

$nextMondaysNeed = range(1,10);
$nextMondaysArray = array($dia->format('Y-m-d'));

foreach($nextMondaysNeed as $number)
{
    $nextMondaysArray[] = $dia->modify('+7 day')->format('Y-m-d');
}

print_r($nextMondaysArray);

Following link of view.

  • Hello Bruno, a plus in your reply would be instead of adding a fixed date to TODAY, could put $dia = new DateTime(date('Y-m-d', time()));

  • Hello Everson, thank you. In case you catch the current date, you can simply leave as new Datetime(). No need to enter values, PHP itself sets the date as the current.

  • I think he wants the next 10 Mondays and not "the next one," plus he needs to add

  • @Bruno Rigolon - Thank you and Everson very much!

  • @Brunorigolon got it. I looked at the documentation and you’re really correct! The default arrow class constructor at the current date ( public __construct ([ string $time = "now" [, DateTimeZone $timezone = NULL ]] ))

  • Gilherme, finding the next one is easier, so I can already add up to the amount I’m going to need here, my main question was this, know what would be the next second!

Show 1 more comment

1

If you use any php version smaller than 5.3, use strtotime() :

$dataStr = "2010-11-24";
$timestamp = strtotime($dataStr);
echo date("d", $timestamp);

If you use a version larger than or equal to 5.3, you can use this :

$string = "2010-11-24";
$date = DateTime::createFromFormat("Y-m-d", $string);
echo $date->format("d");

Ref : Stack

  • Yes, true. I got confused in writing, thanks.

1

Although the author already has an answer, I will put here my contribution to those who go through problems involving programming logic in PHP.

Name the cattle..

It is very common for programmers to name strange functions and variables, or words from another language. This makes it difficult to solve problems, often of the author of the code himself. So whenever possible, change $x for $quantidadeAtual ... etc. Often the code can become more extensive, but the solution of problems and errors become much easier to identify, because of the good writing, which generates a good reading.

Procedural thinking

Often a problem because it is not well defined appears to be a programming problem (language resources, syntax, native functions) and it is not. Think you are a painter, and the language features are your color palette. Maybe you just need to be a little creative to solve a problem, and not necessarily resources or additional knowledge. Except in cases where you do not completely master the 'palette', which is the basic one. Some PHP functions return in strings, which can make your life difficult at times. At the end of this post, I will show that it is possible to solve this problem in particular, without using the native functions of dates. Which shows that you’re not stuck with any method of development, and that you have 'n' ways of solving a problem. A good exercise, is to enumerate in a paper (even real paper), what steps you would do to solve a certain problem. That’s natural language! No PHP, C#, JAVA.. Good English itself.

Do not follow cake recipe

Not even this post is a cake recipe. There are situations that you will write the variable with strange names; quit implementing without a strategy; put loops like [$j][$i][$m] or worse...and all these cases, at least at some point will be situations worth explaining. Someone may want to keep a code short of a loop, have copied and pasted code, or used someone else’s class, etc. The point here is, programming logic is always the way, regardless of your method of implementing. It follows proposed solution, with extreme opposite examples:

<?php header ('Content-type: text/html; charset=UTF-8');

$limiteDoMes = 31; // Essa linha estabelece um limite de dias para o mês
$agenda = array(12, 13, 17, 21, 29); // Array que guarda todos os dias agendados

$diasAgendados = count($agenda); // Conta quantos dias tem agendado, para aplicação saber quantas vezes terá que fazer sua tarefa até parar

$diasCorridos = 0; // Estabelece uma partida para a tarefa ser realizada
    while ($diasCorridos < $diasAgendados) // Enquanto (while) a quantidade de dias corrigos na análise, for menor que a quantidade de dias agendados, faça a tarefa abaixo
    {
        $proximaSegunda = $agenda[$diasCorridos] + 7; // Calcula a proxima segunda de cada dia agendado
        $segundaDoMesSeguinte = $agenda[$diasCorridos] + 7 - $limiteDoMes; // Calcula a proxima segunda se cair no mês seguinte

        if ($proximaSegunda > $limiteDoMes) // Se a próxima segunda cair no mês seguinte, escreva esse texto
        {
            echo "A próxima segunda feira depois do dia $agenda[$diasCorridos] será no mês seguinte, do dia $segundaDoMesSeguinte ";
        }
            else{ // Caso contrário, se cair neste mês, escreva isso
                echo "A próxima segunda feira depois do dia $agenda[$diasCorridos] será $proximaSegunda<br>";

            }
        $diasCorridos++; // Depois da tarefa executada, adicione 1, a dias corrigos, e faça a tarefa de novo, como uma roleta
    }

    ?>

Version of the same solution in traditional coding

<?php
header('Content-type: text/html; charset=UTF-8');

$lm     = 31;
$agenda = array(12,13,17,21,29); 

$da = count($agenda); 

$dc = 0; 
while ($dc < $da) 
                {
                $ps  = $agenda[$dc] + 7; 
                $sms = $agenda[$dc] + 7 - $lm;  seguinte

                if ($ps > $lm) 
                                {
                                echo "A próxima segunda feira depois do dia $agenda[$dc] será no mês seguinte, do dia $sms ";
                } else { 
                                echo "A próxima segunda feira depois do dia $agenda[$dc] será $ps<br>";

                }
                $dc++; 
}

?>

0

Dry form that works in more programming languages.

// 1 SEGUNDA 
// 2 TERCA 
// 3 QUARTA 
// 4 QUINTA 
// 5 SEXTA 
// 6 SABADO 
// 7 DOMINGO

$diaDaSemana = 3; // ALTERE PELO DIA DA SEMANA DA DATA
$xx = (1 - diaDaSemana + 7) % 7;
echo date('d/m/Y', strtotime('+'.$xx.' days', strtotime('14-07-2014')));// ALTERE 14-07-2017 pela data a ser adicionado os dias

date is next Monday. if you want the next Tuesday change

  $xx = (1 - diaDaSemana + 7) % 7;

for

  $xx = (**2** - diaDaSemana + 7) % 7;
  • in any language, do NEVER calculate dates/hours/periods on hand, for sure your language already has something ready. Moreover, it is not all countries that the week begins on Monday :o)

  • In this case you can inform the first day of the week:' public Static int Dow(this Datetime date, Dayofweek startDayOfWeek = Dayofweek.Sunday) { Return (date.Dayofweek - startDayOfWeek + 7) %7 + 1; }'

  • I agree that most languages already have something ready

Browser other questions tagged

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