How to Add millis to Date in Swift without loosing precession

1. Date(timeIntervalSince1970: TimeInterval(millis) / 1000)

It's easy to convert Date to millis, to add millis but the way back in all examples I came across like Date(timeIntervalSince1970: TimeInterval(millis) / 1000) We're loosing the precession.

How to Add millis to Date in Swift without loosing precession ?

A TimeInterval value is always specified in seconds That is when I devide millis I get lower in terms of precession. Instead of millis new created Date is based on seconds. After a while working with the same datetime I get for that datetime value in millis like 1615877999999 instead 1615878000000 like it was at the beginig

2. Thinking about nanosecond .nanosecond, value: step, to: Date())

INT_MAX = 2147483647

INT64_MAX = 9223372036854775807

I need to add - 2700000000000 nanosecond = 2700 sec (that is Int is not an option)

a nanosecond is 1/1,000,000 of millis

I'm confused about this function, because value is Int type, instead of Int64?! .nanosecond, value: step, to: Date())

You can calculate everything in Int64 and split them manually to nanoseconds, seconds, and hours when adding it to date (can't cleanly separate into two, unfortunately).


Given Double has 53-bit precision, it's very curious that you'd be losing precision so quickly. You're nowhere near year 2255 for it to start losing microseconds (not milliseconds, mind you).

1 Like

I got it, we really keep precession

1616595803373 - d = Date().toEpochMilli() -
1616595803373.0 - t = TimeInterval(d)
1616595803.373 - t / 1000
▿ 2021-03-24 14:23:23 - Date(timeIntervalSince1970: t / 1000)
1616595803373 - Date(timeIntervalSince1970: t / 1000).toEpochMilli()

I guess I was distracted by docs phrase "A TimeInterval value is always specified in seconds"
Need to think over what was the real issue

Thank you for helping

Terms of Service

Privacy Policy

Cookie Policy