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

@Apps  

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

LIke

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

   

@Apps  

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

   

Hacking with Swift is sponsored by Play

SPONSORED Play is the first native iOS design tool created for designers and engineers. You can install Play for iOS and iPad today and sign up to check out the Beta of our macOS app with SwiftUI code export. We're also hiring engineers!

Click to learn more about Play!

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.