XWiśniowiecki
XWiśniowiecki

Reputation: 1843

Is DateTimeToString in Delphi XE5 doesn't work?

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?

Upvotes: 0

Views: 1402

Answers (1)

David Heffernan
David Heffernan

Reputation: 613521

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.

Upvotes: 5

Related Questions