Is DateTimeToString in Delphi XE5 doesn't work?

五迷三道 提交于 2020-01-03 05:29:10

问题


I have small piece of code:

  DateTimeToString(DiffString, 't.zzz', TDT);
    ShowMessage('TDT: ' + DateTimeToStr(TDT));
    ShowMessage('DiffString: ' + DiffString);

which result with first ShowMessage gives random nice DateTime TDT value... second where DiffString is exacly 00:00.000

Could anyone check it in other IDE?


回答1:


In fact DateTimeToString works just fine and is behaving exactly as designed. It is doing precisely what you asked it to.

Here is the SSCCE that you should have provided:

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  DiffString: string;
  TDT: TDateTime;

begin
  TDT := Date;
  DateTimeToString(DiffString, 't.zzz', TDT);
  Writeln('TDT: ' + DateTimeToStr(TDT));
  Writeln('DiffString: ' + DiffString);
end.

Output:

TDT: 04/02/2014
DiffString: 00:00.000

The reason is, and I am guessing here, that your date time comes from a call to Date. Or perhaps your date time is an uninitialized variable.

Whichever way, it is clear that the time part is zero. Into DiffString you put the time and not the date. That is what the t.zzz format string means.


Try again with a date time containing a non-zero time:

{$APPTYPE CONSOLE}

uses
  SysUtils;

var
  DiffString: string;
  TDT: TDateTime;

begin
  TDT := Now;
  DateTimeToString(DiffString, 't.zzz', TDT);
  Writeln('TDT: ' + DateTimeToStr(TDT));
  Writeln('DiffString: ' + DiffString);
end.

Output

TDT: 04/02/2014 11:16:43
DiffString: 11:16.942

Of course, t.zzz is a bad choice of format. It combines the short time format with milliseconds. As you can see, on my machine, the default short time format omits seconds. So you get hours, minutes and milliseconds. You'll need to re-think your format string. Perhaps 'hh:nn:ss.zzz' is what you need.



来源:https://stackoverflow.com/questions/21550579/is-datetimetostring-in-delphi-xe5-doesnt-work

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