You are here

function date_calendar_week in Date 8

The calendar week number for a date.

PHP week functions return the ISO week, not the calendar week.

Parameters

string $date: A date string in the format Y-m-d.

Return value

int The calendar week number.

4 calls to date_calendar_week()
DateAPITest::testDateAPI in date_api/lib/Drupal/date_api/Tests/DateAPITest.php
@todo.
date_views_argument_handler_simple::get_default_argument in date_views/includes/date_views_argument_handler_simple.inc
Set the empty argument value to the current date, formatted appropriately for this argument.
date_views_plugin_pager::query in date_views/includes/date_views_plugin_pager.inc
Transfer date information from the argument to the view so the pager theme can use it and update the date argument value to whatever is set by the pager.
template_preprocess_date_views_pager in date_views/theme/theme.inc
Preprocess function for Date pager template.

File

date_api/date_api.module, line 848
This module will make the date API available to other modules. Designed to provide a light but flexible assortment of functions and constants, with more functionality in additional files that are not loaded unless other modules specifically include them.

Code

function date_calendar_week($date) {
  $date = substr($date, 0, 10);
  $parts = explode('-', $date);
  $date = new DrupalDateTime($date . ' 12:00:00', 'UTC');

  // If we are using ISO weeks, this is easy.
  if (config('date_api.settings')
    ->get('iso8601')) {
    return intval($date
      ->format('W'));
  }
  $year_date = new DrupalDateTime($parts[0] . '-01-01 12:00:00', 'UTC');
  $week = intval($date
    ->format('W'));
  $year_week = intval(date_format($year_date, 'W'));
  $date_year = intval($date
    ->format('o'));

  // Remove the leap week if it's present.
  if ($date_year > intval($parts[0])) {
    $last_date = clone $date;
    date_modify($last_date, '-7 days');
    $week = date_format($last_date, 'W') + 1;
  }
  elseif ($date_year < intval($parts[0])) {
    $week = 0;
  }
  if ($year_week != 1) {
    $week++;
  }

  // Convert to ISO-8601 day number, to match weeks calculated above.
  $iso_first_day = 1 + (variable_get('date_first_day', 0) + 6) % 7;

  // If it's before the starting day, it's the previous week.
  if (intval($date
    ->format('N')) < $iso_first_day) {
    $week--;
  }

  // If the year starts before, it's an extra week at the beginning.
  if (intval(date_format($year_date, 'N')) < $iso_first_day) {
    $week++;
  }
  return $week;
}