且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Delphi XE5中的DateTimeToString不起作用吗?

更新时间:2023-12-02 10:34:46

实际上 DateTimeToString 可以正常工作,并且行为完全符合设计。

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

这里是您应该提供的SSCCE:

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.

输出:


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

原因是,我想在这里,您的约会时间来自调用 Date 的时间。也许您的日期时间是未初始化的变量。

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.

无论哪种方式,很明显时间部分为零。将时间而不是日期放入 DiffString 中。这就是 t.zzz 格式字符串的含义。

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.

输出


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





当然, t.zzz 是错误的格式选择。它结合了毫秒的短时间格式。如您所见,在我的计算机上,默认的短时间格式省略了秒。这样您可以获得小时,分钟和毫秒。您需要重新考虑格式字符串。也许‘hh:nn:ss.zzz’是您所需要的。


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.