Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

IF Then problem

Status
Not open for further replies.

MLNorton

Programmer
Nov 15, 2009
134
US
I have a Delphi 2007 procedure to determine the numerical value of the first Monday in the current year. My code is as follows:
Var
WeekDay: integer;
MyDate: TDateTime;
begin
Decodedate(Date,Y,M,D);
MyDate := EncodeDate(Y,1,1);
WeekDay := DayOfWeek(MyDate);
if WeekDay = 1
then
MyDate := MyDate + 1;
If WeekDay = 2
Then
MyDate := MyDate;
If WeekDay = 3
Then
MyDate := MyDate + 6;
If WeekDay = 4
Then
MyDate := MyDate + 5;
If WeekDay = 5
Then
MyDate := MyDate + 4;
If WeekDay = 6
Then
MyDate := MyDate + 3;
if WeekDay = 7
Then
MyDate := MyDate + 2;

For 2012 January 1st My Date is 4909 and WeekDay is 2. When I iterate through the code the line MyDate := MyDate + 1; is skipped.

Why? What is causing this?
 
This function should return the first Monday of a given year (input the desired year), from there you can get the numerical value of the date.

Code:
function FirstMondayOfYear(Year: Word): TDate;
begin
   case DayOfWeek(EncodeDate(year, 1, 1)) of
      1: Result := EncodeDate(year, 1, 2);
      2: Result := EncodeDate(year, 1, 1);
      3: Result := EncodeDate(year, 1, 7);
      4: Result := EncodeDate(year, 1, 6);
      5: Result := EncodeDate(year, 1, 5);
      6: Result := EncodeDate(year, 1, 4);
      else
         Result := EncodeDate(year, 1, 3);
   end;
end;
 
Perhaps a simpler function would be
Code:
[b]function[/b] FirstMondayInYear( datum: TDateTime ): TDateTime;
[b]const[/b]
  Monday = 2;
[b]begin[/b]
  result := EncodeDate( YearOf( datum ), 1, 1 );  // Assume 1 Jan of year of supplied date is a Monday.
  [b]while[/b] DayOfWeek( result ) <> Monday [b]do[/b]          // While this is not a Monday
    result := result + 1;                         // Add one day to date
[b]end[/b];

Andrew
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top