Author: Tomas Rutkauskas
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".
1 unit Forma;
2
3 interface
4
5 uses
6 SysUtils, WinTypes, WinProcs, Messages, Classes, Graphics, Controls,
7 Forms, Dialogs, StdCtrls;
8
9 type
10 TForma1 = class(TForm)
11 Edit1: TEdit;
12 Label1: TLabel;
13 Label2: TLabel;
14 Label3: TLabel;
15 GetWeekBtn: TButton;
16 Label4: TLabel;
17 procedure GetWeekBtnClick(Sender: TObject);
18 procedure FormCreate(Sender: TObject);
19 private
20 { Private declarations }
21 function HowManyDays(pYear, pMonth, pDay: word): Integer;
22 public
23 { Public declarations }
24 end;
25
26 var
27 Forma1: TForma1;
28
29 implementation
30
31 {$R *.DFM}
32
33 uses
34 Inifiles;
35
36 procedure TForma1.FormCreate(Sender: TObject);
37 var
38 WinIni: TInifile;
39 begin
40 WinIni := TIniFile.Create('WIN.INI');
41 WinIni.WriteString('intl', 'sShortDate', 'MM/dd/yyyy');
42 WinIni.Free;
43 end;
44
45 function TForma1.HowManyDays(pYear, pMonth, pDay: Word): Integer;
46 var
47 Sum: Integer;
48 pYearAux: Word;
49 begin
50 Sum := 0;
51 if pMonth > 1 then
52 Sum := Sum + 31;
53 if pMonth > 2 then
54 Sum := Sum + 28;
55 if pMonth > 3 then
56 Sum := Sum + 31;
57 if pMonth > 4 then
58 Sum := Sum + 30;
59 if pMonth > 5 then
60 Sum := Sum + 31;
61 if pMonth > 6 then
62 Sum := Sum + 30;
63 if pMonth > 7 then
64 Sum := Sum + 31;
65 if pMonth > 8 then
66 Sum := Sum + 31;
67 if pMonth > 9 then
68 Sum := Sum + 30;
69 if pMonth > 10 then
70 Sum := Sum + 31;
71 if pMonth > 11 then
72 Sum := Sum + 30;
73 Sum := Sum + pDay;
74 if ((pYear - (pYear div 4) * 4) = 30) and (pMonth > 2) then
75 inc(Sum);
76 HowManyDays := Sum;
77 end;
78
79 procedure TForma1.GetWeekBtnClick(Sender: TObject);
80 var
81 ADate: TDateTime;
82 EditAux: string;
83 Week, year, month, day: Word;
84 begin
85 EditAux := Edit1.Text;
86 ADate := StrToDate(EditAux);
87 Label1.Caption := DateToStr(ADate);
88 DecodeDate(Adate, Year, Month, Day);
89 case DayOfWeek(ADate) of
90 1: Label4.Caption := 'Sunday';
91 2: Label4.Caption := 'Monday';
92 3: Label4.Caption := 'Tuesday';
93 4: Label4.Caption := 'Wednesday';
94 5: Label4.Caption := 'Thursday';
95 6: Label4.Caption := 'Friday';
96 7: Label4.Caption := 'Saturday';
97 end;
98 Week := (HowManyDays(year, month, day) div 7) + 1;
99 Label3.Caption := 'Week No. ' + IntToStr(Week);
100 end;
101
102 end.
|