Get week number of the year

Posted in DateTime

Try this algorithm:

var
  Year, Month, Day: Word;
...
procedure TForm1.Button1Click(Sender: TObject);
var
  YourDate, JunFirst: TDateTime;
  Week, More, Days: Integer;
  DaysLeft: Real;
begin
  YourDate:=StrToDate(Edit1.Text);
  DecodeDate(YourDate, Year, Month, Day);
  JunFirst:=EncodeDate(Year, 1, 1);
  case DayOfWeek(YourDate) of
    1   : More:=0;
    2..7: More:=1;
  end;
  Days:=Trunc(YourDate-JunFirst)+1;
  Week:=(Days div 7)+More;
  DaysLeft:=Days mod 7;
  case DayOfWeek(JunFirst) of
    1   : More:=1;
    2..7: More:=9-DayOfWeek(JunFirst);
  end;
  if (DaysLeft-More>=0) then Week:=Week+1;
  Label2.Caption:='Week number '+IntToStr(Week);
end;