Delphi Programming

and software in general.

Wednesday, September 10, 2008

Snippet: Convert Java time to TDateTime

I am currently working on an application that need to extract content from a Java Web Service using a SOAP interface. The interface delivers all timestamps as Java timestamps (64-bit integer - UTC time in milliseconds before or after the start of January 1, 1970), so I need to convert them to TDateTime for further processing in the Delphi code.

First, I convert it to a Windows filesystem time - which is similar to the Javatime, except from the start time offset and the time resolution. Next, I convert the filetime to Windows UTC time, and adjust for the timezone - simplified to just use the default - ie current local timezone. The final step is to convert the system time constant to a TDateTime.

The whole thing is done with blatant disregard of the tradition of checking return values from the two system calls. The less optimistic of you may choose to check for return values equaling zero to indicate an error.


uses
Windows, SysUtils; // Time functions

function JavaTimeToDateTime(javatime:Int64):TDateTime;
// java time -> Win32 file time -> UTC time
// adjust to active time zone -> TDateTime
var
UTCTime, LocalTime: TSystemTime;
begin
FileTimeToSystemTime(TFileTime(Int64(javatime + 11644473600000) * 10000), UTCTime);
SystemTimeToTzSpecificLocalTime(nil, UTCTime, LocalTime);
Result := SystemTimeToDateTime(LocalTime);
end;
FYI: 11644473600000 * 10000 = 1 Jan 1970 in Windows File Time