title: iOS - Moon Calculation for Moonrise and Moonset
body: <p>I'm trying to translate a library written in Javascript in order to implement it in Objective C for my iOS application.</p>
  
  <p>The link to the JavaScript library : <a href="https://github.com/mourner/suncalc" rel="nofollow noreferrer">https://github.com/mourner/suncalc</a></p>
  
  <p>I got different values for Moonrise and Moonset.</p>
  
  <p>The Javascript library returns : </p>
  
  <pre><code>moonrise = Mon Nov 28 2016 06:43:49 GMT+0100 (CET)
  moonset  = Mon Nov 28 2016 17:10:33 GMT+0100 (CET)
  </code></pre>
  
  <p>My Objective C implementation returns : </p>
  
  <pre><code>moonrise : 2016-11-28 02:00:00 +0000
  moonset  : 2016-11-28 01:00:00 +0000
  </code></pre>
  
  <p>I'm facing an issue with this functions : </p>
  
  <pre><code>// date/time constants and conversions
  
  var dayMs = 1000 * 60 * 60 * 24,
      J1970 = 2440588,
      J2000 = 2451545;
  
  function toJulian(date) { return date.valueOf() / dayMs - 0.5 + J1970; }
  
  function toDays(date)   { return toJulian(date) - J2000; }
  
  function hoursLater(date, h) {
      return new Date(date.valueOf() + h * dayMs / 24);
  }
  </code></pre>
  
  <p>My Objective C implementation : </p>
  
  <pre><code>// date/time constants and conversions
  
  #define dayMS 1000 * 60 * 60 * 24
  #define J1970 2440588
  #define J2000 2451545
  
  -(double)toJulian:(NSDate *) date
  {
      return ([date timeIntervalSince1970] * 1000) / dayMS - 0.5 + J1970;
  }
  
  -(double)toDays:(NSDate *) date
  {
      double tj = [self toJulian:date];
  
      return tj - J2000;
  }
  
  
  
    -(NSDate *)hoursLater:(NSDate *) date :(int) h
  {
      double d = ([date timeIntervalSince1970] * 1000) + h * dayMS / 24;
  
      NSTimeInterval seconds = d / 1000;
      NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:seconds];
  
      return newDate;
  }
  </code></pre>
  
  <p>I can't see any mistakes, but my values are false.</p>
  
  <p><em>Test Example :</em></p>
  
  <p><strong>Javascript Test</strong></p>
  
  <pre><code>var date = new Date();
  var d  = toDays(date);
  console.log("d = " + d);
  </code></pre>
  
  <p>d = 6175.947204432916</p>
  
  <p><strong>Objective C Test</strong></p>
  
  <pre><code>NSDate *today = [NSDate date];
  double d = [self toDays:today];
  NSLog(@"d = %f", d);
  </code></pre>
  
  <p>d = 127900386826537.265625</p>
  
  <p>If you find something, please let me know. </p>