-2

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.

  • Please show the actual code you are using, and how you are checking whether it produces the result you are expecting. And FYI, the correct result for `1552274340690` is `51159-08-14 04:51:30 UTC`. `2019-03-11 11:19:00 UTC` would be `1552303140` instead. That is a HUGE difference in timestamps. – Remy Lebeau Mar 11 '19 at 04:50
  • @RemyLebeau yes sorry, I copied a different utc value. Already updated the post. – Francis Carillo Mar 11 '19 at 04:51
  • `UnixToDateTime()` works correctly. You are clearly working with the wrong timestamp to begin with. Where are you getting the `sUnixTime` value from? How do you know it is a Unix timestamp and not something else? – Remy Lebeau Mar 11 '19 at 04:54
  • @RemyLebeau actually it's from an api result and not much clear what is the format since cannot find description from the document. But according to the online converter I used, that gives the right result, it is converting from epoch timestamp milliseconds or seconds to corresponding datetime value. – Francis Carillo Mar 11 '19 at 04:59
  • @RemyLebeau I did something and gives me somehow a correct result but needs to get the local datetime from it. What I did is divide nUnixTime to 1000, not using the div operator, but rather using just the forward slash then do the rest of the conversion and seem to work. I'm not sure why or how, maybe you can confirm, thanks a lot. – Francis Carillo Mar 11 '19 at 05:28

1 Answers1

4

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

MBo
  • 77,366
  • 5
  • 53
  • 86