Search code examples
datetimedelphiunix-timestampepoch

Delphi: UnixTime string to DateTime gives unexpected result


I am trying to convert a unixtime string to datetime but it give's a wrong result. I am using Delphi XE2 and uses UnixToDateTime function of Dateutils to convert the unixtime string but no luck. I also used a different function I found in the web still the same result. Below are the necessary informations:

Unixtime string value is 1552274340690
The result is "51159-08-14 04:51:30" which should be this "3/11/2019, 11:19:00 AM". The result I got was from an online converter.

Below sample code using UnixToDateTime of System.DateUtils:

var
 nUnixTime : Int64;
begin
 nUnixTime := StrtoInt64(sUnixTime); //sUnixTime = 1552274340690;
 Result = UnixToDateTime(nUnixTime);

Below sample code I found in the web:

const
 UnixStartDate: TDateTime = 25569.0;
var
 nUnixTime : Int64;
begin
 nUnixTime := StrtoInt64(sUnixTime); //sUnixTime = 1552274340690;
 Result := (nUnixTime / 86400) + UnixStartDate; 

Please help, thanks a lot.


Solution

  • Small test

    Caption:=DateTimeToStr(UnixToDateTime(SecondsBetween(StrToDate('01.01.1970'), Now)));` 
    

    gives correct current time.

    Note that UnixTime for now is measured in seconds

    1552307060
    1552274340690
    

    while your value (in the second line) is in milliseconds.

    So you can divide it by 1000 to get value acceptable by UnixToDateTime function