any idea how I figure out if it's currently night/day or sunrise/dawn based on time and location of the user?
I haven't found anything useful that I could use within either the client or backend.
What makes it tricky is the hour doesn't necessarily define if it is night and day, this depends pretty much on the year, month, day, hour and geo coordinates.
For clarification... to emulate something like this.
A way to approximate this would be very useful as well.
Hope that someone can help!
You can do as I did and use this public domain Sun.py module to compute the position of the sun relative to positions on the Earth. It's pretty old, but has worked well for me for many years. I made a few superficial modifications to it to be more up-to-date with Python 2.7, such as making the few classes in it new-style, but for the most part it's unchanged.
Here's one module I created, called sunriseset.py, which shows how to use it to calculate the sunrise and sunset times for a specific location given its geographic coordinates and timezone. The referenced
timezone
module is an implementation of thetzinfo
abstract base class described in thedatetime
module's documentation ontzinfo
objects.PyEphem can be used to calculate the time to the next sunrise and sunset. Building upon a blog post I found and the documentation of rise-set, your problem can be solved as follows. Lets assume I am your user, and my location is Oldenburg (Oldb), Germany.
Notes
lat
andlon
need to be strings but ephem does not complain if they are floats.Prerequisites
This should work with at least Python 2.7 (with
pip-2.7 install pyephem
) and Python 3.2 (withpip-3.2 install ephem
).Make sure to have a network time protocol client running on the system. E.g. on Debian Linux:
Make sure to have the correct timezone set on your system. E.g. on Debian Linux:
A concise description of an algorithm to calculate the sunrise and sunset is provided by the United States Naval Observatory, available here:
http://edwilliams.org/sunrise_sunset_algorithm.htm
In addition to providing the date and location, you also need to select a Zenith angle (at which the sun will be considered to have "risen" or "set") - the page linked has several options.
Update
Because the linked page is no longer available, I am quoting its text below. Note that the formulae included are in a pseudo-code-like form, rather than JavaScript.