Converting UNIX time to TDateTime/String


I need a function to convert UNIX time to the equivalent TDateTime or string.


Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Hi Robert,

I assume you already have the UNIX time somehow retrieved and need to convert it now. In which format does the UNIX time appear?

Ciao, Mike
RLancasterAuthor Commented:
It is an signed long indiciating the number of seconds since 01/01/1970 at 00:00h.

I need to convert this to TDateTime.
A yes, I rember. Well, here's the solution:

function UnixTimeToDateTime(const UnixTime: Integer): TDateTime;

  FileTime: TFileTime;
  SystemTime: TSystemTime;
  I: Int64;
  // first convert unix time to a Win32 file time
  I := Int64(UnixTime) * Int64(10000000) + 116444736000000000;
  FileTime.dwLowDateTime := DWORD(I);
  FileTime.dwHighDateTime := I shr 32;

  // now convert to system time
  FileTimeToSystemTime(FileTime, SystemTime);

  // and finally convert the system time to TDateTime
  Result := SystemTimeToDateTime(SystemTime);

Ciao, Mike

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
RLancasterAuthor Commented:
An extra 50 points bonus for a prompt and most interestingly coded responses I have ever seen !!!

Well done !!!
Thank you :-) And the solution is very easy to understand. Unix time is the seconds from 1/1/1970 as you already wrote. Win32 file time is 100 nanoseconds from 1/1/1601. So multiplication by 10000000 converts the seconds into 100 nanoseconds units and 116444736000000000 is a constant offset (also in 100 ns units) from 1601 to 1970.

The rest is just a bit time format conversion.

Ciao, Mike
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today

From novice to tech pro — start learning today.