Xcqtion
Xcqtion

Reputation: 271

Calculating sunrise/sunset times in Javascript

I have a time, and a given latitude in degrees. Is there any method of calculating the time of sunrise and sunset in Javascript with this information?

Upvotes: 26

Views: 31023

Answers (4)

Abdennour TOUMI
Abdennour TOUMI

Reputation: 93531

Sun-time is enough if you use JavaScript as programming language of server-side (Node.js).

npm install sun-time ; 

Then :

var sun=require('sun-time');
 sun('Tunis') // -> i.e : return {rise:"05:00",set:"18:36"}

for more details

Upvotes: 3

pollaris
pollaris

Reputation: 1321

This javascript program

https://github.com/Triggertrap/sun-js

calculates sunrise and sunset times based only on the latitude and longitude of your location, which can be obtained automatically from GPS as follows:

<script>
var x = document.getElementById("demo");
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    } else {
        x.innerHTML = "Geolocation is not supported by this browser.";
    }
}
function showPosition(position) {
    x.innerHTML = "Latitude: " + position.coords.latitude + 
    "<br>Longitude: " + position.coords.longitude; 
}
</script> 

It includes a readme file to explain how to use it. It calculates the zenith, and is very accurate.

Upvotes: 2

esamatti
esamatti

Reputation: 18973

SunCalc seems to do what you want

SunCalc is a tiny BSD-licensed JavaScript library for calculating sun position, sunlight phases (times for sunrise, sunset, dusk, etc.), moon position and lunar phase for the given location and time

https://github.com/mourner/suncalc

Upvotes: 39

Floris
Floris

Reputation: 46435

The relevant code can be found at http://www.esrl.noaa.gov/gmd/grad/solcalc/

You need longitude, latitude, and date. It would be helpful to indicate if you want the answer in local time, or universal time. The corrections needed to get true accuracy (and the definition you use for "sunrise" and "sunset") all play a huge role in the effectiveness of the calculation.

If you just want to know "approximately" when the sun is level with the horizon "on the assumption of a spherical earth, a circular orbit around the sun, and without atmospheric distortion" - then the whole shooting match reduces to something quite manageable. But if you want the real answer you have to work through about 600 lines of script of the above website.

For approximations, you can see this earlier answer

Upvotes: 10

Related Questions