How to convert Delphi TDateTime to String accurate to microseconds

I need to convert TDateTimeto microsecondString precision . In the case of millisecond precision, you can use formatting:

DateTimeToString(Result, 'd.m.yyyy hh:nn:ss.zzz', dateTime);

but I need three more digits (microseconds).

You can take the fractional part and divide it by 1/86400/1000000, but I'm looking for a more efficient way to convert it.

+4
source share
1 answer

The accuracy of the date-time depends on how far from "zero".

Delphi TDateTimeis actually an 8-byte floating point Double, with zero 12/31/1899 12:00:00 am.

TDateTime, :

function AddQuantumToDateTime(const dt: TDateTime): TDateTime;
var
   overlay: Int64 absolute Result;
begin
   Result := dt;
   overlay := overlay+1;
end;

, TDateTime . , , :

  • 12/31/1899: 0
  • 1/1/1900: 0
  • 1/1/1970: 314
  • 1/1/2000: 629
  • 1/1/2016: 629
  • 1/1/2038: 629
  • 1/1/3000: 5 029
  • 1/1/4000: 10 058
  • 1/1/5000: 20,117
  • 1/1/6000: 20,117
  • 1/1/7000: 20,117
  • 1/1/8000: 40,233
  • 1/1/9000: 40,233
  • 1/1/9999: 40,233

DateTime .

FILETIME Windows 100ns, SYSTEMTIME :

typedef struct _SYSTEMTIME {
  WORD wYear;
  WORD wMonth;
  WORD wDayOfWeek;
  WORD wDay;
  WORD wHour;
  WORD wMinute;
  WORD wSecond;
  WORD wMilliseconds;
} SYSTEMTIME, *PSYSTEMTIME;

Microsoft SQL Server new datetime2(7) datetime (100 ) :

SELECT CAST('20160802' AS datetime2(6)) AS TheNow

TheNow
==========================
2016-08-02 00:00:00.000000

, TDateTime , ( ) . :

function DateTimeToStrUs(dt: TDatetime): string;
var
    us: string;
begin
    //Spit out most of the result: '20160802 11:34:36.'
    Result := FormatDateTime('yyyymmdd hh":"nn":"ss"."', dt);

    //extract the number of microseconds    
    dt := Frac(dt); //fractional part of day
    dt := dt * 24*60*60; //number of seconds in that day
    us := IntToStr(Round(Frac(dt)*1000000));

    //Add the us integer to the end:
    // '20160801 11:34:36.' + '00' + '123456'
    Result := Result + StringOfChar('0', 6-Length(us)) + us;
end;

:

DateTimeToStrUs(Now)

:

20160802 11: 34: 36.482364

+4

Source: https://habr.com/ru/post/1627277/


All Articles