# How to calculate how many degrees the Sun is from the horizon?

Given a position on earth (latitude/longitude, and maybe also height relative to sea-level) and a time, what's the algorithm to find how many degrees the Sun is from the horizon?

And the same for the opposite, given a location and date, how do you calculate the time when the Sun will be such-and-such degrees from the horizon (such as to calculate astronomical dusk and dawn)?

1. Calculate the position of the Sun in ecliptic coordinates. By definition, the ecliptic latitude of the Sun is 0. If you are willing to accept the inaccuracy introduced by pretending the Earths orbit is circular rather than elliptical, and can look up the ecliptic coordinates of the Sun for some time relatively close to the time for which you want the position, you can make the approximation $$\lambda = \lambda_D + \frac{360^\circ}{365.242191\, \mathrm{days}} \Delta D$$ where $\lambda_D$ is the ecliptic longtitude of the sun at date $D$, and $\Delta D$ is the number of days between the time you want and date $D$.
2. Convert the ecliptic coordinates to equatorial coordinates. Because the ecliptic latitude of the Sun is 0, this reduces to: $$\alpha = \tan^{-1} \left[\frac{\sin \lambda \cos \epsilon}{\cos \lambda}\right]$$ $$\delta = \sin^{-1} [\sin \epsilon \sin \lambda]$$ where $\epsilon$ is the obliquity of the ecliptic, currently about 23.4378 degrees, but it does change over time.
3. Now you need to convert the right ascension in ecliptic coordinates to an hour angle at the time and longitude of interest. To do this, you need to calculate the local sidereal time. (You can do this by first calculating the Greenwich Sidereal Time (GST), and converting to local sidereal time. Sidereal time and solar time agree at the autumn equinox, so look up the autumn equinox in UT, and calculate the time between then and the time of interest. A sidereal year is one day longer than a solar year, so convert that duration from solar time to sidereal time by multiplying by $\frac{365.242191+1}{365.242191}$. Then convert Greenwich sidereal time to local sidereal time by subtracting the (west) longitude. Be careful with the units here: 24 hours is 360 degrees is $2 \pi$ radians.) Then you can calculate the hour angle: $$H=\mathrm{LST} - \alpha$$.
4. Once you have the hour angle, $H$, you can calculate the altitude, $a$ (which is half of the conversion to horizon coordinates): $$a=\sin^{-1} [\sin \delta \sin \phi + \cos \delta \cos \phi \cos H]$$ where is $\phi$ is the geographic latitude of interest.