Handling Week Number   PHP


Summary

Example of handling week number


<?php
$date_str = '2010-01-01';
print_r("$date_str <br>");

$date = new DateTime($date_str);
$date_y = $date->format('Y');
$date_W = $date->format('W');
print_r("$date_y $date_W <- This expression is wrong <br>");

print_r("-----<br>");

$date->sub(new DateInterval('P1D'));
$date_y = $date->format('Y');
$date_W = $date->format('W');
print_r("$date_y $date_W<br>"); // correct expression
$date->add(new DateInterval('P1D')); // rewind

$date->add(new DateInterval('P3D'));
$date_y = $date->format('Y');
$date_m = $date->format('m');
$date_W = $date->format('W');
print_r("$date_y $date_W<br>");

$date = (new DateTime())->setISODate($date_y, $date_W); // assign with (year, week)

$date_s = $date->format('Y-m-d'); // start day of week (monday)
$date->add(new DateInterval('P6D'));
$date_e = $date->format('Y-m-d'); // end day of week (sunday)

print_r("$date_s ~ $date_e<br>");

$date_str = '2010-02-01';
print_r("$date_str <br>");

$date = new DateTime($date_str);
$date_y = $date->format('Y');
$date_m = $date->format('m');
$date_W = $date->format('W');

// Week number of this month, using 04 is due to ISO_8601.
$date_mW = $date_W - date('W', strtotime("$date_y-$date_m-04")) + 1;
print_r("$date_W $date_mW");


Result

2010-01-01
2010 53 <- This expression is wrong
-----
2009 53
2010 01
2010-01-04 ~ 2010-01-10
2010-02-01
05 1

References


Tags

#date  #datetime  #week 


[ Edit (Author only) ]