title: In Swift, how can I get an NSDate from a dispatch_time_t?
body: <p>"Walltime" is a little-known time format used by Grand Central Dispatch. Apple talks about it here:</p>
  
  <p><a href="https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/" rel="noreferrer">https://developer.apple.com/library/ios/documentation/Performance/Reference/GCD_libdispatch_Ref/</a></p>
  
  <p>There are some things it's really handy for, though, but it's a sticky wicket. It's hard to make it play nice with other time formats, which is what my question's about.</p>
  
  <p>I can make a walltime by turning an <code>NSDate</code> into a <code>timespec</code>, and then using with <code>dispatch_walltime</code>:</p>
  
  <pre><code> let now = NSDate().timeIntervalSince1970
   let nowWholeSecsFloor = floor(now)
   let nowNanosOnly = now - nowWholeSecsFloor
   let nowNanosFloor = floor(nowNanosOnly * Double(NSEC_PER_SEC))
   var thisStruct = timespec(tv_sec: Int(nowWholeSecsFloor),
   tv_nsec: Int(nowNanosFloor))
   let wallTime = dispatch_walltime(&amp; thisStruct, 0)
  </code></pre>
  
  <p>But lord love a duck, I can't figure out how to get it back into an <code>NSDate</code>. Here's my try:</p>
  
  <pre><code>public func toNSDate(wallTime: dispatch_time_t)-&gt;NSDate {
      let wallTimeAsSeconds = Double(wallTime) / Double(NSEC_PER_SEC)
      let date = NSDate(timeIntervalSince1970: wallTimeAsSeconds)
      return date
  }
  </code></pre>
  
  <p>The resulting <code>NSDate</code> is not just off, but somewhat hilariously off, like five hundred years or something. As Martin R pointed out, the problem is that <code>dispatch_time_t</code> is an opaque value, with an undocumented representation of time.</p>
  
  <p>Does anyone know how to do this?</p>
  
  <p>EDIT: if the process of creating the walltime is confusing, this is basically what's going on:</p>
  
  <p><code>NSDate</code> defines time with a <code>Double</code>, and everything after the decimal point is the nanoseconds. <code>dispatch_time</code>, which can create a walltime, defines time with <code>UInt64</code>, so you have to convert between <code>Double</code> and <code>UInt64</code> to use it. To do that conversion you need to use a <code>timespec</code>, which takes seconds and nanoseconds as separate arguments, each of which must be <code>Int</code>.</p>
  
  <p>A whole lotta convertin' going on!</p>