Delphi中如何知道类型变量是TDateTime、TDate和TTime

Joh*_*gon 5 delphi rtti tdatetime

我需要知道类型变量 TDateTime、TDate 和 TTime。

任何人都知道如何做到这一点?

我使用了下面的代码,结果是“不是 TDateTime”、“不是 TDate”、“不是 Ttime”


program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  System.Rtti,
  System.SysUtils;

var
  DateTime, Date,Time: TValue;

begin

  DateTime:= StrToDateTime( '01/01/2013 01:05:09' );
  if ( DateTime.TypeInfo = System.TypeInfo(TDateTime) ) then
    Writeln( 'Is TDateTime' )
  else
    Writeln( 'Is NOT TDateTime' );

  Date:=  StrToDate( '01/01/2015' );
  if ( Date.TypeInfo = System.TypeInfo(TDate) ) then
    Writeln( 'Is TDate' )
  else
    Writeln( 'Is NOT TDate' );

 Time:=  StrToTime( '01:01:02' );
  if ( Date.TypeInfo = System.TypeInfo(TTime) ) then
    Writeln( 'Is TTime' )
  else
    Writeln( 'Is NOT TTime' );

 Readln;

end.
Run Code Online (Sandbox Code Playgroud)

谢谢

Ste*_*nke 5

Implicit的操作符重载TValue得了你。

当您将StrToDateTime, StrToDateand的结果分配StrToTime给 a 时,TValue它使用最匹配的Implicit运算符重载TValueis Extended

也请记住,所有这三个函数返回TDateTime所以即使有对操作符重载TDateTimeTDate并且TTime它不会按预期方式工作。

要获得正确的结果,您必须在将值分配给TValue变量时明确指定类型:

DateTime := TValue.From<TDateTime>(StrToDateTime( '01.01.2013 01:05:09' ));

Date:= TValue.From<TDate>(StrToDate( '01.01.2015' ));

Time:= TValue.From<TTime>(StrToTime( '01:01:02' ));
Run Code Online (Sandbox Code Playgroud)


Mar*_*ams 2

以防万一您尝试确定 StrToDateTime 的结果类型:

type
  TDateType = (dtDate, dtDateTime, dtTime);

function getDateType(date: TDateTime): TDateType;
begin
  if Trunc(date) = date then // Or DateOf(date), if available
  begin
    Result := dtDate;
  end
  else
  begin
    if Trunc(date) = 0 then // Or DateOf(date), if avaialble
    begin
      Result := dtTime
    end
    else
    begin
      Result := dtDateTime;
    end;
  end;
end;

// Sample
var
  result: TDateType;
begin
  result := getDateType(StrToDateTime('01/01/2013 01:05:09')); // dtDateTime
  result := getDateType(StrToDateTime('01/01/2015')); // dtDate
  result := getDateType(StrToDateTime('01:01:02')); // dtTime
  // One caveat
  result := getDateType(StrToDateTime('01/01/2013 00:00:00')); // dtDate
end;
Run Code Online (Sandbox Code Playgroud)

或者,您可以使用TryStrToDateTryStrToTimeTryStrToDateTime函数。