UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

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?

2      

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

2      

@Apps  

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

2      

Hacking with Swift is sponsored by Essential Developer

SPONSORED Join a FREE crash course for mid/senior iOS devs who want to achieve an expert level of technical and practical skills – it’s the fast track to being a complete senior developer! Hurry up because it'll be available only until April 28th.

Click to save your free spot now

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

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

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.