Using the RTTI system in Delphi 2010, is there any way to find out if a property is a TDateTime? It's currently treating it as a double whenever I call back asVariant and also if I check the property type. Is this due to the fact it can only see the base type? (TDateTime = double)

  • Well, a date/time is always a double in which the integer part represent days, while fractional part represents minutes and seconds (as part of a day) – Marco Oct 20 '11 at 13:49
  • I understand it is a double technically but is there any way I can use RTTI to check if its defined as a TDateTime originally – Barry Oct 20 '11 at 13:59
up vote 24 down vote accepted

Try checking the Name property of the TRttiProperty.PropertyType

I don't have Delphi 2010, but this works in XE.

{$APPTYPE CONSOLE}

uses
  SysUtils,
  Classes,
  Rtti;

type
  TMyClass =class
  private
    FDate: TDateTime;
    FProp: Integer;
    FDate2: TDateTime;
    FDate1: TDateTime;
  public
   property Date1 : TDateTime read FDate1  Write FDate1;
   property Prop : Integer read FProp  Write FProp;
   property Date2 : TDateTime read FDate2  Write FDate2;
  end;

var
 ctx : TRttiContext;
 t :  TRttiType;
 p :  TRttiProperty;
begin
 ctx := TRttiContext.Create;
 try
   t := ctx.GetType(TMyClass.ClassInfo);
   for p in  t.GetProperties do
    if CompareText('TDateTime',p.PropertyType.Name)=0 then
     Writeln(Format('the property %s is %s',[p.Name,p.PropertyType.Name]));
 finally
   ctx.Free;
 end;
  Readln;
end.

this code returns

the property Date1 is TDateTime
the property Date2 is TDateTime
  • 1
    +1, hats off; I didn't believe it's possible – TLama Oct 20 '11 at 14:02
  • +1 thank you so much, saved me re-writing a shedload of code :) – Barry Oct 20 '11 at 14:03
  • Glad to help you :) – RRUZ Oct 20 '11 at 14:04
  • 1
    +1 Nice job, as always. – Ken White Oct 20 '11 at 16:27
  • 3
    This also works since at least Delphi 5 with the older TypInfo methods. – Ken Bourassa Oct 20 '11 at 20:51

Key point here while defining type is the type directive. These two definitions are different:

Type
  TDateTime = Double; // here p.PropertyType.Name returns Double

but

Type
  TDateTime = type Double; // here p.PropertyType.Name returns TDateTime

or 

Type
  u8 = type Byte; // here p.PropertyType.Name returns u8

but

Type
  u8 = Byte; // here p.PropertyType.Name returns Byte !
  • Obviously OP didn't declare the types in question, so technically this is not an answer, but you're quite right and this extra explanation is good information though. +1 – NGLN Mar 26 '12 at 5:21

Your Answer

 
discard

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Not the answer you're looking for? Browse other questions tagged or ask your own question.