Javascript code to determine sunrise and sunset times

If I have a specific time and a latitude measurement in degrees, is there a way to determine the sunrise and sunset times using JavaScript?

Answer №1

For all your sun position calculation needs, SunCalc is the way to go!

SunCalc is a fantastic BSD-licensed JavaScript library that can calculate sun position, sunlight phases (including sunrise, sunset, dusk), moon position, and lunar phase based on location and time.

Check out SunCalc on GitHub here

Answer №2

To find the necessary code, visit

Ensure you have longitude, latitude, and date available. Specify whether you prefer the answer in local time or universal time. The accuracy of the calculations relies heavily on required corrections (and your definitions of "sunrise" and "sunset").

If you're looking for an "approximate" estimate of when the sun is at horizon level based on simple assumptions about Earth's shape, orbital path, and lack of atmospheric influence, the process can be simplified. However, for precise results, be prepared to dissect approximately 600 lines of script from the provided website.

For rough estimations, refer to this previous response

Answer №3

Maximize Your Sun-Time by incorporating JavaScript on the server-side with Node.js.

npm install sun-time ; 

After installation, use the following code:

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

Explore for more insights

Answer №4

This unique javascript application

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

derives sunrise and sunset timings solely based on the latitude and longitude coordinates of your current location, which can be automatically fetched through GPS like this:

<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 contains a readme guide for usage instructions. The calculations are made at the zenith point and offer high accuracy.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

My attempts to utilize the input tag alongside Three.js have been unsuccessful

Currently delving into game development with Three.js, I'm utilizing the Web GL renderer to take over the entire browser window. A new challenge has arisen as I attempt to incorporate a chat box within this setup. To achieve this, I've placed an ...

Adjusting the size of the canvas and its elements on-the-fly

As a novice in JavaScript, I am seeking guidance with patience. I am currently working on creating a sandbox drawing feature for a website using JavaScript and the canvas element. My main objective is to resize the canvas dynamically while maintaining pro ...

Adjust the color of a glyphicon when the text changes using Jquery

Here is a snippet of code that I am working with : <div class="col-xs-6"> @Html.TextBoxFor(model => model.TagName, new {@class = "textBoxTextFormat", @id = "newTagText"}) </div> <div class="col-xs-3" > <a href="#" id="addNe ...

What is the best way to specify a function parameter as the `QUnit` type using TypeScript in conjunction with QUnit?

In my project, which is partially written in TypeScript and licensed under MIT, I am utilizing QUnit. I have some TypeScript functions that require QUnit as a parameter, and I would like to define their types based on its interface from the typings. For e ...

Are multiple instances of ajax being executed within the modal?

Currently, I am working on a feature that requires an Ajax request. To begin with, the process involves opening a modal by clicking a button with the class '.open-email-modal'. Within this modal, there are two input fields to enter registration d ...

Issue with Bootstrap Modal Field failing to expand

I am currently working on a Bootstrap Modal that utilizes jQuery to generate a list within my form. My main objective is to have the email section dynamically expand as the length of the email input increases. Update: You can find the modal I am using at ...

Enhance/Revamp a JavaScript library function

Currently, I'm utilizing a fantastic open-source JavaScript library known as timeline.verite.co. This timeline library works flawlessly upon page load. However, I encounter odd errors when attempting to repaint the timeline under specific conditions. ...

Iterating through an array within an array in a React component

I am currently working on a basic React app where I have nested arrays and need to iterate over all the content. Here is my code snippet so far: {recipes.map((recipe) => ( <Recipe key={recipe.uid} title={r ...

IP Address SSL/TSL Certificate

Here is a curl command I am using to grant permission to a local user: curl "https://10.10.135.35/9880/grant_permission?user=username&role=role" -k I am looking to achieve the same purpose using fetch in JavaScript. Here's an example code snippe ...

In node.js, create a variable that stores the result of an SQL query to count the number of rows in

Within my node.js javascript program, I am working with a (postgres sql) table. My objective is to determine the number of rows in the table and store this value in a variable (n) for further use in the code. In response to feedback, I have included more ...

I'm experiencing difficulties with a JavaScript slideshow in Vegas

After installing the vegas jQuery plugin to my project using npm, I encountered issues when attempting to use it according to the documentation. Despite linking the required vegas.min.js and vegas.min.css files in my HTML, the plugin doesn't appear to ...

The issue of underscorejs being undefined arises when trying to load it using both XMLHttpRequest and

I am attempting to dynamically load underscorejs using XMLHttpRequest and eval function function includeScriptSync(scriptUrl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.open("GET", scriptUrl, false); xmlhttp.onreadystatechange = function() ...

Tips for sharing a global variable in Node.js multi-cluster mode while running Socket.IO on an NGINX load balancer but using fork mode with PM2

My socket.io app is currently running with NGINX load balancing on 6 cores, distributing the load among them. When I use pm2 list myapp, it shows that the app is running in fork mode but spanning across 6 processes due to NGINX load balancing. │ myapp-1 ...

Implementing JavaScript to Retrieve and Insert Full HTML Tags into a Textarea

I am currently trying to extract an HTML source code value and insert it into a specific textarea or div upon clicking a button. However, I am encountering issues where I am not receiving the entire HTML tags - it seems to begin with a Meta tag and is remo ...

Error Handling with Firebase Cloud Firestore and State Management in Vue using Vuex (firebase.firestore.QuerySnapshot)

Upon examining the code, I noticed an issue with docChanges. It seems to be a function, but when I try to use docChanges().doc.data().userId, I encounter the error message: store.js?3bf3:21 Uncaught TypeError: Cannot read property 'doc' of undefi ...

Guide to exporting specific files in Node.js or Deno

Utilizing the export keyword in JavaScript allows us to export any content from one file to another. Is there a way to restrict exports to specific files, preventing other files from importing them? export const t = { a: 'this will only be exported fo ...

How can I protect a text or script file from being accessed or downloaded by entering its URL directly into the browser address bar?

While working on my JSP file, I have incorporated some Java-script code but to safeguard it from being visible to clients, I decided to store it in a separate codescript.js file and load it using ajax like so: $.ajax({ cache: true, dataType: "script ...

Ensure that divs remain in a static position within the dialog box

Within the jQueryUI dialog, I have gray boxes at the top and bottom of the visible area represented by the .nav elements. I want these gray boxes to stay fixed in their position even when scrolling within the dialog. Despite setting position: absolute, the ...

Guide to utilizing various functions, with equations, within a specific scope in angularJS

myApp.controller('incomeController', ['$scope', function($scope) { $scope.pay = 0; $scope.hours = 0; $scope.tax=0.19297; $scope.total = function() { return $scope.pay * $scope.hours;} $scope.taxTotal ...

"An error appeared while using jQuery's mouseover function - unrecognized

Here is the code snippet I am working with: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div class="portal" style="width:50px;height:50px;background:black" data-target="whatever"></div> < ...