List days of the week with month and year PHP

Asked

Viewed 1,355 times

0

I am wanting to print the days of the week separated by the number of the week of a given month: What I have so far is:

function days_week($date = NULL){

$date = ($date == NULL) ? date('m/d/Y') : $date;
$ts = strtotime($date);
$year = date('o', $ts);
$week = date('W', $ts);

$return = [];
for($i = 0; $i <= 6; ++$i) {
    $ts = strtotime($year.'W'.$week.$i);

    $week_month = date('w', strtotime($ts));
    $return[$week_month][$i]['day_week'] = date("d/m/Y", $ts);
    //echo $return['day_week'];
    switch(date("l", $ts)){
        case 'Sunday':
            $return[$week_month][$i]['day_name'] = "domingo";
        break;
        case 'Monday':
            $return[$week_month][$i]['day_name'] = "segunda";
        break;
        case 'Tuesday':
            $return[$week_month][$i]['day_name'] = "terça";
        break;
        case 'Wednesday':
            $return[$week_month][$i]['day_name'] = "quarta";
        break;
        case 'Thursday':
            $return[$week_month][$i]['day_name'] = "quinta";
        break;
        case 'Friday':
            $return[$week_month][$i]['day_name'] = "sexta";
        break;
        case 'Saturday':
            $return[$week_month][$i]['day_name'] = "sábado";
        break;
    };
    //echo " - ".$return['day_name'];
    switch(date("M", $ts)){
        case 'Jan':
            $return[$week_month][$i]['month_name'] = 'janeiro';
        break;
        case 'Feb':
            $return[$week_month][$i]['month_name'] = 'fevereiro';
        break;
        case 'Mar':
            $return[$week_month][$i]['month_name'] = 'março';
        break;
        case 'Apr':
            $return[$week_month][$i]['month_name'] = 'abril';
        break;
        case 'May':
            $return[$week_month][$i]['month_name'] = 'maio';
        break;
        case 'Jun':
            $return[$week_month][$i]['month_name'] = 'junho';
        break;
        case 'Jul':
            $return[$week_month][$i]['month_name'] = 'julho';
        break;
        case 'Aug':
            $return[$week_month][$i]['month_name'] = 'agosto';
        break;
        case 'Sep':
            $return[$week_month][$i]['month_name'] = 'setembro';
        break;
        case 'Oct':
            $return[$week_month][$i]['month_name'] = 'outubro';
        break;
        case 'Nov':
            $return[$week_month][$i]['month_name'] = 'novembro';
        break;
        case 'Dec':
            $return[$week_month][$i]['month_name'] = 'dezembro';
        break;
    }
}
    return json_encode($return);
}

Using:

echo "<pre>";
print_r(days_week("04/01/2018"));
echo "</pre>";

Returns the following:

{
"4": [
      {
        "day_week": "25/03/2018",
        "day_name": "domingo",
        "month_name": "março"
      },
      {
         "day_week": "26/03/2018",
         "day_name": "segunda",
         "month_name": "março"
      },
      {
         "day_week": "27/03/2018",
         "day_name": "terça",
         "month_name": "março"
      },
      {
         "day_week": "28/03/2018",
         "day_name": "quarta",
         "month_name": "março"
      },
      {
         "day_week": "29/03/2018",
         "day_name": "quinta",
         "month_name": "março"
      },
      {
         "day_week": "30/03/2018",
         "day_name": "sexta",
         "month_name": "março"
      },
      {
         "day_week": "31/03/2018",
         "day_name": "sábado",
         "month_name": "março"
      }
    ]
  }

But you can see that the result is wrong, because it shows the result until day 31/03, when it was to show from day 01/04 onwards... strange that with the other days works normal... anyone has any tips? Grateful!


Goal I wish is a JSON of this format:

USER INPUT

MES: 04 YEAR: 2018

OUTPUT (JSON):

{
"1": [
      {
        "day_week": "01/04/2018",
        "day_name": "domingo",
        "month_name": "abril"
      },
      {
         "day_week": "02/04/2018",
         "day_name": "segunda",
         "month_name": "abril"
      },
      {
         "day_week": "03/04/2018",
         "day_name": "terça",
         "month_name": "abril"
      },
      ...
      ...
      {
         "day_week": "07/04/2018",
         "day_name": "sabado",
         "month_name": "abril"
      }
     ],
    "2": [
          {
             "day_week": "08/04/2018",
             "day_name": "domingo",
             "month_name": "abril"
          },
          {
             "day_week": "09/04/2018",
             "day_name": "segunda",
             "month_name": "abril"
          },
           ...................

I ask for forgiveness from friends because I really had not been "understandable" =) I think I have now made it clear, 1, 2 ... is the number of the week in the month. And I need the list of days, as described in JSON

  • 1

    Couldn’t figure out the goal... Is it to do the seven days including the inserted day? How many days are you supposed to return? You must be more specific in your goal

  • 2

    As @Pedromartins said, you need to be more specific in what you want to present... contextualize and indicate the goal please.

  • 1

    I arranged @Pedromartins and Fernando, grateful

  • @Hermus let me know if there are any mistakes, okay? Hug!

  • @Hermus would you have any comment to make about my reply? You managed to test it?

  • 1

    @Andreicoelho was traveling, sorry for the delay, was show, was not exactly what I thought, but met my need. Grateful

  • @Hermus if you need any more help, let me know here. Hug!

  • @Hermus if I have to change anything I’ll help you.

Show 3 more comments

1 answer

3


ERRORS IDENTIFIED IN YOUR CODE

  1. As shown by you in the desired result, with the input of the day 01/04/2018 you would like the dates presented of a total of 5 weeks (in April). But in your code you have a loop on maximum 7 days, ie only 1 week in the result. So I switched your for by a while(true). That 'while' is broken as soon as the month ends.
  2. Another error relates to formatting timestamp. When I said who did not identify the error, in fact I did not really understand because it happens. But I know it exists and I will show it to follow.

First you turn the date into timestamp:

$date = "04/01/2018";
$ts = strtotime($date);

The Value returned is 1522533600 Then you rescue the year and the week in the year:

$year = date('o', $ts); // isso aqui retorna o ano. OK! (2018)
$week = date('W', $ts); // isso retorna o numero da semana no ano. OK! (13)

Inside the loop you try to use the following code:

$ts = strtotime($year.'W'.$week.$i);

That returns the value of 1521932400. Which is different from the value of the first day 1522533600. If you convert this value:

// $i = 0
echo date("m/d/Y", strtotime($year.'W'.$week.$i));

You will have the date of 25/03/2018. Exactly the wrong value of json.

I created an alternative to get the result. See:

$dia = "01";
$mes = "04";
$ano = "2018";
$data = $dia."-".$mes."-".$ano;

$dia_da_semana_array = array('Domingo', 'Segunda', 'Terca', 'Quarta', 'Quinta', 'Sexta', 'Sabado'); // lista
$meses_array = array('', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'); // lista
$dia_da_semana_inicial = date('w', strtotime($data)); // pega o dia da semana em inteiro
$dia_da_semana_inicial_string = $dia_da_semana_array[$dia_da_semana_inicial];  // pega o dia da semana  em string

$arraySemanas = array(); // lista das semanas

$x = (int)$dia_da_semana_inicial;
$y = 0;

$semana = 1;
while(true){

    // insere no array
    $indexMes = (int)$mes;
    $arraySemanas[$semana][$y]['day_week'] = $data; 
    $arraySemanas[$semana][$y]['day_name'] = $dia_da_semana_array[$x];
    $arraySemanas[$semana][$y]['month_name'] = $meses_array[$indexMes];

    // verifica se mudou o mês
    $data = date('d-m-Y', strtotime("+1 day", strtotime($data)));
    $dataVerifi = explode("-", $data);
    if($dataVerifi[1] != $mes){
        // se mudou o mes para o loop
        break;
    }

    if($x == 6){
        $x = 0;
        $y = 0;
        $semana++;
    } else {
        $x++;
        $y++;
    }

}

print_r(json_encode($arraySemanas));

See working on ideone

Your job would look like this:

function days_week($date = NULL){

    $date = ($date == NULL) ? date('d/m/Y') : $date;

    $date = explode("/", $date);
    $dia = $date[0];
    $mes = $date[1];
    $ano = $date[2];
    $data = $dia."-".$mes."-".$ano;


    $dia_da_semana_array = array('Domingo', 'Segunda', 'Terca', 'Quarta', 'Quinta', 'Sexta', 'Sabado'); // lista
    $meses_array = array('', 'Janeiro', 'Fevereiro', 'Março', 'Abril', 'Maio', 'Junho', 'Julho', 'Agosto', 'Setembro', 'Outubro', 'Novembro', 'Dezembro'); // lista
    $dia_da_semana_inicial = date('w', strtotime($data)); // pega o dia da semana em inteiro
    $dia_da_semana_inicial_string = $dia_da_semana_array[$dia_da_semana_inicial];  // pega o dia da semana  em string

    $arraySemanas = array(); // lista das semanas

    $x = $dia_da_semana_inicial;
    $y = 0;

    $semana = 1;
    while(true){

        // insere no array
        $indexMes = (int)$mes;
        $arraySemanas[$semana][$y]['day_week'] = str_replace("-","/",$data); 
        $arraySemanas[$semana][$y]['day_name'] = $dia_da_semana_array[$x];
        $arraySemanas[$semana][$y]['month_name'] = $meses_array[$indexMes];

        // verifica se mudou o mês
        $data = date('d-m-Y', strtotime("+1 day", strtotime($data)));
        $dataVerifi = explode("-", $data);
        if($dataVerifi[1] != $mes){
            // se mudou o mes para o loop
            break;
        }

        if($x == 6){
            $x = 0;
            $y = 0;
            $semana++;
        } else {
            $x++;
            $y++;
        }

    }

    return json_encode($arraySemanas);
}

echo days_week("01/04/2018");

I hope it helps you.

  • how does to list only the week of the date informed? example day 01/04/2018, it returns only the days from day 01 to day 07.

  • 1

    @Fernandamaria you can use the date('w', strtotime('01/04/2018')). This function will return you an integer from 0 to 6... 0 = 'Sunday' and 6 = 'Saturday' ... knowing the day of the week the date is, you can use DateTime to add or subtract dates. Example: https://stackoverflow.com/a/15564182/9303032

  • 1

    @Fernandamaria created an example in ideone https://ideone.com/qyAkZp

  • 1

    thank you so much :)

Browser other questions tagged

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