JavaScript Class for Sunrise and Sunset Calculations
A JavaScript class for calculating sunrise and sunset times based on latitude, longitude, and date.
FeedbackBy Preston Hunt, 23 January 2011


I wanted to add a feature to Presto's Sidebar Clock that would automatically adjust the color of the clock based on the time of day. Because the clock has support for international time zones, I thought it might be helpful to know whether it was day or night in the other time zones that a user tracks.

There are a lot of web sites that calculate this information. And most of them use JavaScript. And some sites, such as NOAA, had a generous license that would allow reuse of the code. Unfortunately, extracting the code and making it usable proved more difficult than it should have been.

Eventually, I found a page with the calculations and decided it would be faster to go ahead and write it myself from the grounds up. I've generalized it a bit and made it a class in the hopes that other developers can use it.


Here's how you use it:

var tokyo = new SunriseSunset( 2011, 1, 19, 35+40/60, 139+45/60); 
tokyo.sunriseUtcHours()      --> 21.8199 = 21:49 GMT
tokyo.sunsetUtcHours()       --> 7.9070  = 07:54 GMT
tokyo.sunriseLocalHours(9)   --> 6.8199  = 06:49 at GMT+9
tokyo.sunsunsetLocalHours(9) --> 16.9070 = 16:54 at GMT+9
tokyo.isDaylight(1.5)        --> true


The code is available under an Apache 2.0 License on Pastebin.

Are you using my code in your project? Did you find a bug? Let me know!

blog comments powered by Disqus