WWDC22 SALE: Save 50% on all my Swift books and bundles! >>

Is there a way to convert DispatchTime value to Date on iOS?

Forums > Swift


I am working with an internal API, that I cannot modify, that delivers time in DispacthTime structure.


let time:DispatchTime = myAPI.getTime()

I am trying to debug that, to see which value is that. So, I ask: Is there a way to convert that value to Date on iOS?


I think the unhelpful answer is, "Sure. You do some arithmetic and there you go." The helpful answer is probably, "Nope, there is no built-in language function that accepts a DispatchTime (or even a dispatch_time_t) and gives you back a Date that would agree with your understanding of a clock/calendar on the wall."

From the documentation of DispatchTime: "A point in time relative to the default clock, with nanosecond precision." A close look at DispatchTime reveals that it's a UInt64, so that means it's probably a number of nanoseconds. Date has an initializer that accepts a TimeInterval, but that's a) a Double and b) a number of seconds and c) relative to either the reference date or the Unix epoch.

So, you get to figure out what's the zero time for "the default clock", then do some math to figure out how to transform nanoseconds after that into seconds after the appropriate reference time and then you can call the appropriate Date initializer.

Or, I guess, you can get the DispatchTime.now value and compare it to your dispatch time that the API gave you and then do what you want with the delta (which is in nanoseconds).



Thanks for your answer. I will try to figure it out.


Hacking with Swift is sponsored by Emerge

SPONSORED Optimize your app’s startup time, binary size, and overall performance using Emerge’s advanced app optimization and monitoring tools. Reliably measure app size, speed up your app's startup time with Emerge's Launch Booster, and much more. Emerge is actively used by many of the top mobile development teams in the world.

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Reply to this topic…

You need to create an account or log in to reply.

All interactions here are governed by our code of conduct.

Unknown user

You are not logged in

Log in or create account

Link copied to your pasteboard.