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.

Windows, SysUtils; // Time functions

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


  1. FYI: SystemTimeToTzSpecificLocalTime function cannot be used to convert historical datetime in common case in XP and 2000 (I am not sure about Vista). Microsoft guys say only current datatime converted correctly and even those ones not always (it depends on some windows updates). We had a big trouble there and wrote special convertion function that uses real historical data :).


  2. Thanks, Alec! Useful info! I assume the Daylight Saving Time factor can be tricky as the dates have changed over the years.
    I guess a more reliable approach would be to calculate and add the time offset yourself. For my use, the the dates don't go very far back and the software runs in a controlled environment (with regards to Windows updates/patches) - so it is less of a problem for me.