SolarPosition

A javascript library to calculate solar position and sun rise, set and transit times. It is based on the calculation and code published by National Renewable Energy Laboratory here, and should be very accurate.

The code is available on GitHub here.

The Calculation

JulianDay

The part of this code that calculates Julian days can be used separately. Julian Days are a date format commonly used in astronomy. They count the number of days since noon, January 1st, 4713 BC. Time periods less than a day can be represented as fractional days.

There are four ways to create a JulianDay object.

  1. You can directly instantiate one with the Julian Day number, e.g. var jd = new JulianDate(2456168.2).
  2. You can convert a standard javascript date to a Julian Day, e.g. var jd = JulianDate.fromDate(new Date())
  3. You can create one based on the individual components, e.g. var jd = JulianDate.fromValues(year, month, day, hour, minute, second, millisecond, tz)
  4. You can create one by copying another date and modifying it, e.g. var jd1 = jd.add(0.5)
Here's an example:

var jd = JulianDay.fromValues(2012, 1, 1, 13, 20, 05, 988);
console.log(jd.ephemerisDay(60));
console.log(jd.ephemerisCentury(60));
console.log(jd.ephemerisMillennium(60));

var date = jd.toDate();

Time

More ways of manipulating the time are available with the Time javascript class. Internally, Time instances store the time as fractions of a day.

They can be created

  1. directly from a number with the time in fractions of a day. The integral part of the time is ignored. var time = new Time(5.432)
  2. from a javascript Date. var time = Time.fromDate(new Date())
  3. from the values for hours, minutes, seconds and milliseconds. var time = Time.fromValues(12, 30, 10, 992). They can also be created from a datastructure containing these values.
  4. by copying and modifying another time, e.g. var time1 = time.addHours(2.5) there is also a method for changing the timezone of a Time changeTimeZone which uses addHours.

SolarPosition

To actually perform the calculation, create a SolarPosition object providing as many of the parameters as you can.

var julianDay = JulianDay.fromValues(2012, 1, 1, 13, 20, 05, 988);
var sp = new SolarPosition(julianDay, latitude, longitude, delta_t, elevation, pressure, temperature, slope, azm_rotation, atmos_refract);
console.log(sp.getSunRiseTransitSet());
console.log(sp.getSunPosition());
console.log(sp.calculateGeocentricSunRightAscensionAndDeclination());