Mirror

How to calculate the week from a given date (Views: 103)


Problem/Question/Abstract:

How to calculate the week from a given date

Answer:

The code below tells you which week the specified date is in, and also the corresponding day of the week. The date format it handles is "06/25/1996". You have to create a form named "Forma" with a TEdit named "Edit1", four labels and a button named "GetWeekBtn".


unit Forma;

interface

uses
  SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
  Forms, Dialogs, StdCtrls;

type
  TForma1 = class(TForm)
    Edit1: TEdit;
    Label1: TLabel;
    Label2: TLabel;
    Label3: TLabel;
    GetWeekBtn: TButton;
    Label4: TLabel;
    procedure GetWeekBtnClick(Sender: TObject);
    procedure FormCreate(Sender: TObject);
  private
    { Private declarations }
    function HowManyDays(pYear, pMonth, pDay: word): Integer;
  public
    { Public declarations }
  end;

var
  Forma1: TForma1;

implementation

{$R *.DFM}

uses
  Inifiles;

procedure TForma1.FormCreate(Sender: TObject);
var
  WinIni: TInifile;
begin
  WinIni := TIniFile.Create('WIN.INI');
  WinIni.WriteString('intl', 'sShortDate', 'MM/dd/yyyy');
  WinIni.Free;
end;

function TForma1.HowManyDays(pYear, pMonth, pDay: Word): Integer;
var
  Sum: Integer;
  pYearAux: Word;
begin
  Sum := 0;
  if pMonth > 1 then
    Sum := Sum + 31;
  if pMonth > 2 then
    Sum := Sum + 28;
  if pMonth > 3 then
    Sum := Sum + 31;
  if pMonth > 4 then
    Sum := Sum + 30;
  if pMonth > 5 then
    Sum := Sum + 31;
  if pMonth > 6 then
    Sum := Sum + 30;
  if pMonth > 7 then
    Sum := Sum + 31;
  if pMonth > 8 then
    Sum := Sum + 31;
  if pMonth > 9 then
    Sum := Sum + 30;
  if pMonth > 10 then
    Sum := Sum + 31;
  if pMonth > 11 then
    Sum := Sum + 30;
  Sum := Sum + pDay;
  if ((pYear - (pYear div 4) * 4) = 30) and (pMonth > 2) then
    inc(Sum);
  HowManyDays := Sum;
end;

procedure TForma1.GetWeekBtnClick(Sender: TObject);
var
  ADate: TDateTime;
  EditAux: string;
  Week, year, month, day: Word;
begin
  EditAux := Edit1.Text;
  ADate := StrToDate(EditAux);
  Label1.Caption := DateToStr(ADate);
  DecodeDate(Adate, Year, Month, Day);
  case DayOfWeek(ADate) of
    1: Label4.Caption := 'Sunday';
    2: Label4.Caption := 'Monday';
    3: Label4.Caption := 'Tuesday';
    4: Label4.Caption := 'Wednesday';
    5: Label4.Caption := 'Thursday';
    6: Label4.Caption := 'Friday';
    7: Label4.Caption := 'Saturday';
  end;
  Week := (HowManyDays(year, month, day) div 7) + 1;
  Label3.Caption := 'Week No. ' + IntToStr(Week);
end;

end.

<< Back to main page