Get the week number of a given date  

Send By: Q3 Team
Web : www.q3.nu
Email: dlib@q3.nu
Date: 29/07/99

Tip accessed 995 times

 


Test this code:


 	  procedure TForm1.Button1Click(Sender: TObject);
 	   var
 	       frstDay,toDay : TDateTime;
 	       week : Integer;
 	   begin
 	      frstDay := StrToDate('1/1/96');
 	      toDay := StrToDate(Edit1.Text);
 	      week := Trunc((toDay - frstDay) / 7) + 1;
 	      Label1.Caption := IntToStr(week);
 	   end;






I wait that this other works well:


 function NumSemana(Fecha:string):integer;
 var
    PrimerDia:TDate;
 begin
     {Calculamos primer dia del año}
     {First day of year}
     PrimerDia:=StrToDate('01/01/'+Copy(Fecha,7,2));

     {Calculamos el numero de semana del año}
     {Calculate the week of year number}
     Result:=Trunc(
                  (StrToDate(Fecha)-
                  PrimerDia+
                  DayOfWeek(PrimerDia)-1
                  ) /7)+1;
 end;



This function supposes that the first day of the week is Sunday (just as ago the Función DayOfWeek of Delphi). For me, lifelong, the week it begins in Monday (in Spain it is this way, and I suppose that in other countries it will pass the same thing), so we will have to adapt the function so that it counts the weeks to our pleasure:


 function NumSemana(Fecha:string):integer;
 var
    PrimerDia:TDate;
    DiaDelPrimerDia:integer;
 begin
     {Calculamos primer dia del año}
     {First day of year}
     PrimerDia:=StrToDate('01/01/'+Copy(Fecha,7,2));

     {Calculamos dia de la semana que empieza por lunes}
     {Calculate the day of week, begining by monday instead of Sunday}
     If DayOfWeek(PrimerDia)-1 =0
       then DiaDelPrimerDia:=7
       else DiaDelPrimerDia:=DayOfWeek(PrimerDia)-1;

     {Calculamos el numero de semana del año}
     {Calculate the week of year number}
     Result:=Trunc(
                  (StrToDate(Fecha)-
                  PrimerDia+
                  DiaDelPrimerDia-1
                  ) /7)+1;
 end;



Now, test it and tellme later...