문제

When I use the command line, this query gives me pleasing results (it shows duation, which is what TIMEDIFF is about):

mysql> select timediff(end_time_stamp,start_time_stamp) from test_runs;
+-------------------------------------------+
| timediff(end_time_stamp,start_time_stamp) |
+-------------------------------------------+
| 00:00:07                                  |
| 00:00:11                                  |
| 00:01:23                                  |
+-------------------------------------------+
3 rows in set (0.00 sec)

When I put it in a DB grid in Delphi, the TIMEDIFFs are formatted like 12:00:07 AM, which is not what I want (that looks like a time, not a duration).

I am using AnyDac and when I open the query editor at design time and execute it, the result is also 12:00:07 AM, so it seems that AnyDac is formatting it for some reason.

How can I get output like 00:00:07 (a duration, not a time)?

  • Can I tweak the AnyDac query?
  • Can I explicitly format the output using the MySql statement?
  • Is thare an OnXXX() function which I can code to reformt (and how)?

[Update] Well, this ugly piece of code does what I want, but is there a more elegant way?

SELECT run_id,
       start_time_stamp,
       end_time_stamp,
       CONCAT(CONCAT(CONCAT(CONCAT(LPAD(EXTRACT(HOUR FROM timediff(end_time_stamp,start_time_stamp)), 2, '0'), ":"),LPAD(EXTRACT(MINUTE FROM timediff(end_time_stamp,start_time_stamp)), 2, '0'), ":"), LPAD(EXTRACT(SECOND FROM timediff(end_time_stamp,start_time_stamp)), 2, '0'))) AS duration,
       description

FROM test_runs ORDER BY start_time_stamp DESC
도움이 되었습니까?

해결책

Use the DisplayFormat property of the TField object to get the result you want, for example:

begin
  MyQuery.Open;
  MyQueryField.DisplayFormat := 'hh:nn:ss';
  //or casting a TField to a descendant, like this:
  (MyQuery.FieldByName('duration') as TDateTimeField).DisplayFormat := 'hh:nn:ss';
end;

Edit

I added a cast to TDateTimeField. If your actual field is not an instance of TDateTimeField or a descendant it will result in a EInvalidTypeCast exception, since you have to cast it to the correct class it belongs to.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top