How can I put an ordinal suffix on the end of a date?

2k views Asked by At

I'm using Delphi BDS2006 how can I format the date (01/10/2011) to look something like 1st Oct 2011

I tried using the ShowMessage(FormatDateTime('ddd mmm yyyy', now));

the message I get is Sat Oct 2011

ddd gives me Satand not 1st

Similar way I want to add st,nd,rd,th to the Dates

Is there a built in procedure or function to do this or I have to manually check for the date and assign the suffix to it

I'm currently using this

case dayof(now)mod 10 of
 1 : days:=inttostr(dayof(dob))+'st';
 2 : days:=inttostr(dayof(dob))+'nd';
 3 : days:=inttostr(dayof(dob))+'rd';
 else days:=inttostr(dayof(dob))+'th';

 end;
2

There are 2 answers

0
David Heffernan On BEST ANSWER

There's nothing built in to Delphi to do that form of day. You will have to do it yourself. Like this:

function DayStr(const Day: Word): string;
begin
  case Day of
  1,21,31:
    Result := 'st';  
  2,22:
    Result := 'nd';  
  3,23:
    Result := 'rd';  
  else
    Result := 'th';  
  end;
  Result := IntToStr(Day)+Result;
end;
0
TLama On

Here's the locale independent English version of the same. GetShortMonth is there because ShortMonthNames takes the month abbreviations from the locale settings.

function GetOrdinalSuffix(const Value: Integer): string;
begin
  case Value of
    1, 21, 31: Result := 'st';
    2, 22: Result := 'nd';
    3, 23: Result := 'rd';
  else
    Result := 'th';
  end;
end;

function GetShortMonth(const Value: Integer): string;
begin
  case Value of
    1: Result := 'Jan';
    2: Result := 'Feb';
    3: Result := 'Mar';
    4: Result := 'Apr';
    5: Result := 'May';
    6: Result := 'Jun';
    7: Result := 'Jul';
    8: Result := 'Aug';
    9: Result := 'Sep';
    10: Result := 'Oct';
    11: Result := 'Nov';
    12: Result := 'Dec';
  end;
end;

procedure TForm1.DateTimePicker1Change(Sender: TObject);
var
  Day: Word;
  Month: Word;
  Year: Word;
begin
  DecodeDate(DateTimePicker1.Date, Year, Month, Day);
  ShowMessage(Format('%d%s %s %d', [Day, GetOrdinalSuffix(Day), GetShortMonth(Month), Year]));
end;