NEW: My new book Pro SwiftUI is out now – level up your SwiftUI skills today! >>

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 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 RevenueCat

SPONSORED In-app subscriptions are a pain to implement, hard to test, and full of edge cases. RevenueCat makes it straightforward and reliable so you can get back to building your app. Oh, and it's free if your app makes less than $10k/mo.

Learn 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.