Print the number of each week of a date in specific PHP

2

I am working with dates in php but I can not specify something like what I'm looking for, my problem is to be able to visualize the number of weeks in a specific month I hope I was clear and thank you for your help. EXAMPLE:

  • WEEKS of date = 2018-03-16 (today)

DEPARTURE:

  • WK-9
  • WK-10
  • WK-11
  • WK-12
  • WK-13
asked by JrojasE 16.03.2018 в 23:29
source

3 answers

1

You can do it this way, using the strftime PHP

function
<?php
$date = '2018-03-16';

$firstDay = date('Y-m-01', strtotime($date)); // Tomamos el primer día del mes
$lastDay = date('Y-m-t', strtotime($date)); // Y tomamos el ultimo día del mes

$weeks = array();
// Iteramos sobre todos los días del mes, y agregamos al arreglo las semanas solo si no existen previamente
while ($firstDay < $lastDay) {
    $week = strftime('%V', strtotime($firstDay));
    if (!in_array($week, $weeks)) {
        $weeks[] = strftime('%V', strtotime($firstDay));
    }
    $firstDay = date ('Y-m-d', strtotime($firstDay . ' +1 day'));
}
?>

In the case of today print:

array (size=5)
  0 => string '09' (length=2)
  1 => string '10' (length=2)
  2 => string '11' (length=2)
  3 => string '12' (length=2)
  4 => string '13' (length=2)
    
answered by 17.03.2018 / 00:56
source
2

Your best ally for this would be to use a DateTime object.

Now, in some cases the week starts on Sunday, in others the week starts on Monday.

Let's see an example for each case:

Week starting on Sunday

$fecha = new DateTime('first Sunday of this month');
$esteMes = $fecha->format('m');

while ($fecha->format('m') === $esteMes) {
    echo $fecha->format('W').PHP_EOL;
    $fecha->modify('next Sunday');
}

Exit:

09
10
11
12

Week starting on Monday

$fecha = new DateTime('first Monday of this month');
$esteMes = $fecha->format('m');

while ($fecha->format('m') === $esteMes) {
    echo $fecha->format('W').PHP_EOL;
    $fecha->modify('next Monday');
}

Exit:

10
11
12
13
    
answered by 17.03.2018 в 00:11
1

Try with:

echo date_format($fecha,"W");

The above prints the number of the week of the date reported in the variable $ date

    
answered by 16.03.2018 в 23:37