Know the number of the week of a range of dates

2

I would like to get the number of the week from a range of dates

for example if I have:

$fechaI = '2017-01-'01';
$fechaF = '2017-01-21';

then it's 3 weeks and I want to save it in a array that is

$nSena =[1,2,3];

where 1,2,3 is the number of the week,

example two:

$fechaI = '2017-09-'01';
$fechaF = '2017-09-21';

then:

$nSena =[35,36,37,38];

I tried to do it but what I achieved was the following:

<?php
$fechaI = new DateTime('2017-09-01');
$fechaF = new DateTime('2017-09-21');
$interval = $fechaI->diff($fechaF);
echo floor(($interval->format('%a') / 7)) ; 

and it returns me the number of weeks in that range that would be 4

    
asked by Soldier 08.09.2017 в 20:43
source

3 answers

2

You should try something like this:

$fechaI = new DateTime('2017-09-01');
$fechaF = new DateTime('2017-09-21');
$semanainicio = $fechaI->format("W");
$semanafin = $fechaF->format("W");

for ($i = $semanainicio; $i <=  $semanafin; $i++)
{
    echo $i;
}

format returns the week number in the year. Then all I do is a for to get the list of weeks. Note that even a single week, this code should work (but I did not try it).

    
answered by 08.09.2017 / 20:52
source
3
   
$firstWeek=date('W',strtotime('2017-01-12'));
$lastWeek=date('W',strtotime('2017-09-12'));
echo json_encode(array_keys(array_fill(($lastWeek<$firstWeek?$lastWeek:$firstWeek),abs($lastWeek-$firstWeek),'0')));

Dates may be truncated and not have to be greater than the second, always return the weeks in order.

To save the last line in an array, it would be:

$arr=array_keys(array_fill(($lastWeek<$firstWeek?$lastWeek:$firstWeek),abs($lastWeek-$firstWeek),'0'));
    
answered by 08.09.2017 в 21:36
1

Completing @gbianchi's answer, try to do it like this:

$fechaI = new DateTime('2017-09-01');
$fechaF = new DateTime('2017-09-21');
$semanainicio = (int) $fechaI->format("W"); // Convertimos a entero
$semanafin = (int) $fechaF->format("W");// Convertimos a entero

$nSena = [];
while ($semanainicio <=  $semanafin) {
    $nSena[] = $semanainicio;
    $semanainicio++;
}
echo json_encode($nSena);

The result would be:

[35,36,37,38]

Demo

    
answered by 08.09.2017 в 21:03