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 SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How to rewrite this better 1

Status
Not open for further replies.

morfasie

IS-IT--Management
Mar 28, 2004
85
0
0
ZA
Hi all,

I want to know how to rewrite this better, because I know there must be. I tried enumerations but failed?

I get the month from readline in file and have to convert it to 01,02 etc.


month := leftstr(rightstr(A[8],8),3);
if (month = 'Jan') then
monthnr = '01'
else if (month = 'Feb') then
monthnr = '02'
else if (month = 'Mar') then
monthnr = '03'
else if (month = 'Apr') then
monthnr = '04';

thanks
 
The trick is to use the predefined ShortMonthNames array.

Write a little function along the lines of:
Code:
function GetMonthNumber( month: string ): string;
var
  n: integer;
begin
  n := 13;
  repeat
    Dec( n );
  until ( n = 0 ) or ( ShortMonthNames[n] = month );
  result := IntToStr( n );
end;
This will return the month number as a string or a '0' if the month name is invalid.

It should be called along the lines of:
Code:
procedure TForm1.Button2Click(Sender: TObject);
var
  month: string;
begin
  month := leftstr(rightstr(A[8],8),3);
  ShowMessage( GetMonthNumber( month ) );
end;

Andrew
Hampshire, UK
 
One old trick:

Pat := 'Jan/Feb/Mar/Apr/May.....'

p := pos( MonthStr, Pat );

if p = 0 then Month := 0 else Month := (p-1) div 4 + 1;
 
Unfortunately, grg999's One old trick is slightly buggy. For example, if MonthStr contains /Ap then the code will return 3 instead of 0.

If this is not a problem then the solution can be simplified to:
Code:
pat := 'Jan/Feb/Mar/Apr/May.....'

p := Pos( MonthStr, pat );

month := ( p + 3 ) div 4;

Andrew
Hampshire, UK
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top