You are here

function date_calc_gregorian_to_ISO in Date 6

Same name and namespace in other branches
  1. 5.2 date_php4/date_php4_calc.inc \date_calc_gregorian_to_ISO()
  2. 6.2 date_php4/date_php4_calc.inc \date_calc_gregorian_to_ISO()

Converts from Gregorian Year-Month-Day to ISO Year-WeekNumber-WeekDay

Uses ISO 8601 definitions. Algorithm by Rick McCarty, 1999 at http://personal.ecu.edu/mccartyr/ISOwdALG.txt . Transcribed to PHP by Jesus M. Castagnetto.

Parameters

int $day: The day of the month.

int $month: The month.

int $year: The 4 digit year. Do not add leading 0's for years prior to 1000.

Return value

string The date in ISO Year-WeekNumber-WeekDay format.

2 calls to date_calc_gregorian_to_ISO()
date_calc_week_of_year in date_php4/date_php4_calc.inc
Returns week of the year, first Sunday is first day of first week.
date_php4.inc in date_php4/date_php4.inc

File

date_php4/date_php4_calc.inc, line 278

Code

function date_calc_gregorian_to_ISO($day, $month, $year) {
  $mnth = array(
    0,
    31,
    59,
    90,
    120,
    151,
    181,
    212,
    243,
    273,
    304,
    334,
  );
  $y_isleap = date_is_leap_year($year);
  $y_1_isleap = date_is_leap_year($year - 1);
  $day_of_year_number = $day + $mnth[$month - 1];
  if ($y_isleap && $month > 2) {
    $day_of_year_number++;
  }

  // find Jan 1 weekday (monday = 1, sunday = 7)
  $yy = ($year - 1) % 100;
  $c = $year - 1 - $yy;
  $g = $yy + intval($yy / 4);
  $jan1_weekday = 1 + intval(($c / 100 % 4 * 5 + $g) % 7);

  // weekday for year-month-day
  $h = $day_of_year_number + ($jan1_weekday - 1);
  $weekday = 1 + intval(($h - 1) % 7);

  // find if Y M D falls in YearNumber Y-1, WeekNumber 52 or
  if ($day_of_year_number <= 8 - $jan1_weekday && $jan1_weekday > 4) {
    $yearnumber = $year - 1;
    if ($jan1_weekday == 5 || $jan1_weekday == 6 && $y_1_isleap) {
      $weeknumber = 53;
    }
    else {
      $weeknumber = 52;
    }
  }
  else {
    $yearnumber = $year;
  }

  // find if Y M D falls in YearNumber Y+1, WeekNumber 1
  if ($yearnumber == $year) {
    if ($y_isleap) {
      $i = 366;
    }
    else {
      $i = 365;
    }
    if ($i - $day_of_year_number < 4 - $weekday) {
      $yearnumber++;
      $weeknumber = 1;
    }
  }

  // find if Y M D falls in YearNumber Y, WeekNumber 1 through 53
  if ($yearnumber == $year) {
    $j = $day_of_year_number + (7 - $weekday) + ($jan1_weekday - 1);
    $weeknumber = intval($j / 7);
    if ($jan1_weekday > 4) {
      $weeknumber--;
    }
  }

  // put it all together
  if ($weeknumber < 10) {
    $weeknumber = '0' . $weeknumber;
  }
  return $yearnumber . '-' . $weeknumber . '-' . $weekday;
}