You are here

public static function CalendarHelper::dateWeek in Calendar 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.

Throws

\Exception

3 calls to CalendarHelper::dateWeek()
Calendar::calendarBuildMiniWeek in src/Plugin/views/style/Calendar.php
Build one mini week row.
Calendar::calendarBuildMonth in src/Plugin/views/style/Calendar.php
Build one month.
Calendar::render in src/Plugin/views/style/Calendar.php
Render the display in this style.

File

src/CalendarHelper.php, line 354

Class

CalendarHelper
Defines Gregorian Calendar date values.

Namespace

Drupal\calendar

Code

public static function dateWeek($date) {
  $date = substr($date, 0, 10);
  $parts = explode('-', $date);
  $timezone = new \DateTimeZone('UTC');
  $date = new \DateTime($date . ' 12:00:00', $timezone);
  $year_date = new \DateTime($parts[0] . '-01-01 12:00:00', $timezone);
  $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 = 0;

  // 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;
}