Home Setting dynamicly a property of an object containing datetime
Reply: 1

Setting dynamicly a property of an object containing datetime

John
1#
John Published in 2018-02-12 11:38:36Z

I have a bunch of different methods for creating, calling and setting properties of different objects using Delphi's RTTI. But now I have come to an error where setting a TDateTime triggers an error like: "Cannot convert variant into double". Google doesn't help when searching for this error.

So far, I'm defining an object of any type, for example:

TExample = class
private
  FDateField : TDateTime;
published
  property DateField : TDateTime read FDateField write FDateField;
end;

I'm then putting this object in a TObjectList, and then looping some internal logic that's not really relevant to the problem. But when I come to the DateField property, it triggers the error. I'm trying to set it like this:

objPropValue := '12/02/2018 12:25:00';
objPropName := 'DateField';
if IsPublishedProp(parameterObject, objPropName) then
begin
  SetPropValue(parameterObject, objPropName, objPropValue); <- doesn't work on DateField
end;

This is only a hardcoded example, the objPropValue and Name are set in a loop and can be of any other type. I tried different formatting as well, but I can't seem to find the correct way to do this.

Dsm
2#
Dsm Reply to 2018-02-12 11:55:01Z

Despite the error message, what you are trying to do here is assign a string to a date, which you just can't do. If instead you did this

    objPropValue := '12/02/2018 12:25:00';
    objPropName := 'DateField';
    if IsPublishedProp(parameterObject, objPropName)  then
    begin
      SetPropValue(parameterObject, objPropName, StrToDateTime(objPropValue));
    end;

it would work fine. That is just for illustration, of course. If objPropValue is a variant (which you don't show) you could use

    objPropValue := StrToDateTime('12/02/2018 12:25:00');
    objPropName := 'DateField';
    if IsPublishedProp(parameterObject, objPropName)  then
    begin
      SetPropValue(parameterObject, objPropName, objPropValue);
    end;

instead.

You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.316569 second(s) , Gzip On .

© 2016 Powered by mzan.com design MATCHINFO