Convert unix timestamp to Date failed.

I get and int unix timestamp from database and convert it to timeinterval as some instructions said. But the result date is not correct. the code is as follows:

                let dateValue = try join.get(examDate);
                print (dateValue)
                let timeInterval = TimeInterval(dateValue);
                print(timeInterval)
                let date = Date(timeIntervalSince1970: timeInterval)
                print(date)

the result is as follows:

1709942400000
1709942400000.0
56155-12-02 00:00:00 +0000

by converting 1709942400000 with js Date, we got the value:

>new Date(1709942400000)
2024-03-09T00:00:00.000Z

How can I properly convert unix timestamp to Date object?

Thanks in advance.

Answered by endecotp in 780314022

1709942400000 is milliseconds since 1970, not seconds. Traditional "unix timestamp" values are in seconds; that is what the objC/Swift Date constructor timeIntervalSince1970 is expecting. In contrast the Javascript Date constructor takes milliseconds. If you divide the value by 1000 you'll get the right answer.

Accepted Answer

1709942400000 is milliseconds since 1970, not seconds. Traditional "unix timestamp" values are in seconds; that is what the objC/Swift Date constructor timeIntervalSince1970 is expecting. In contrast the Javascript Date constructor takes milliseconds. If you divide the value by 1000 you'll get the right answer.

Convert unix timestamp to Date failed.
 
 
Q