Mirror

How to calculate the current week (Views: 101)


Problem/Question/Abstract:

How to calculate the current week

Answer:

Solve 1:

There are 2 other functions included which are required for our function. One checks for a leap year, the other returns the number of days in a month (checking the leap year) and the third is the one you want, the week of the year.


function kcIsLeapYear(nYear: Integer): Boolean;
begin
  Result := (nYear mod 4 = 0) and ((nYear mod 100 <> 0) or (nYear mod 400 = 0));
end;

function kcMonthDays(nMonth, nYear: Integer): Integer;
const
  DaysPerMonth: array[1..12] of Integer = (31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31);
begin
  Result := DaysPerMonth[nMonth];
  if (nMonth = 2) and kcIsLeapYear(nYear) then
    Inc(Result);
end;

function kcWeekOfYear(dDate: TDateTime): Integer;
var
  X, nDayCount: Integer;
  nMonth, nDay, nYear: Word;
begin
  nDayCount := 0;
  DecodeDate(dDate, nYear, nMonth, nDay);
  for X := 1 to (nMonth - 1) do
    nDayCount := nDayCount + kcMonthDays(X, nYear);
  nDayCount := nDayCount + nDay;
  Result := ((nDayCount div 7) + 1);
end;


Solve 2:

function CalendarWeek(ADate: TDateTime): integer;

{Author: Ralph Friedman (ralphfriedman@email.com)

Calculates calendar week assuming:
Monday is the 1st day of the week
The 1st calendar week is the 1st week of the year that contains a Thursday

-1 result indicates error.
Any other negative result indicates week 52 or 53 of the previous year.}

var
  day: word;
  dayOne: word;
  firstOfYear: TDateTime;
  month: word;
  monthOne: word;
  prevDayOne: word;
  year: word;
begin
  Result := -1;
  try
    DecodeDate(ADate, year, month, day);
  except
    Exit;
  end;
  case DayOfWeek(EncodeDate(year, 1, 1)) of
    1: dayOne := 2; {Sunday}
    2: dayOne := 1; {Monday}
    3: dayOne := 31; {Tuesday}
    4: dayOne := 30; {Wednesday}
    5: dayOne := 29; {Thursday}
    6: dayOne := 4; {Friday}
    7: dayOne := 3; {Saturday}
  else
    dayOne := 0;
  end;
  case DayOfWeek(EncodeDate(year - 1, 1, 1)) of
    1: prevDayOne := 2; {Sunday}
    2: prevDayOne := 1; {Monday}
    3: prevDayOne := 31; {Tuesday}
    4: prevDayOne := 30; {Wednesday}
    5: prevDayOne := 29; {Thursday}
    6: prevDayOne := 4; {Friday}
    7: prevDayOne := 3; {Saturday}
  else
    prevDayOne := 0;
  end;
  if (prevDayOne = 0) or (dayOne = 0) then
    Exit;
  if dayOne > 4 then
  begin
    Dec(year);
    monthOne := 12
  end
  else
    monthOne := 1;
  firstOfYear := EncodeDate(year, monthOne, dayOne);
  if (ADate < firstOfYear) then
    if (PrevDayOne > 4) then
      Result := -53
    else
      Result := -52
  else
    Result := (Trunc(ADate - firstOfYear) div 7) + 1;
end;

<< Back to main page