Displaying a MySql TIMEDIFF() in a DB grid

一笑奈何 提交于 2019-12-12 04:25:36

问题


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

回答1:


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.



来源:https://stackoverflow.com/questions/15262319/displaying-a-mysql-timediff-in-a-db-grid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!