1

I want to have a website with different UIs based on if it is day or night in client's timezone. right now I have this code based on what I found on internet:

const hours = new Date().getHours()
const isDayTime = hours > 6 && hours < 20

if (isDayTime === True){
    //do this...
}

but the problem is sunrise and sunset is different in each timezone, also it changes through seasons, so considering 6 to 20 as my day time hours is wrong(since it could be night time before 20 in winter).

Is there a way to get day time or night time based on client timezone?

ren
  • 30
  • 7
  • 3
    This may help: https://sunrise-sunset.org/api – Randy Casburn Nov 16 '21 at 18:35
  • The sunrise/set time is different even within the same timezone, you would need lat-lon location of the client to calculate the sunrise/set. – Teemu Nov 16 '21 at 18:37
  • Timezone is longitude so irrelevant (mostly) for sunrise as that's based on latitude. i.e. on a specific day someone in GMT will have sunrise at 8am and someone *at the same latitude* but in EST will also have sunrise at 8am (their local time) (give or take a few minutes based on exactly where in the timezone they are) – freedomn-m Nov 16 '21 at 18:42
  • Thank you @RandyCasburn – ren Nov 18 '21 at 22:48
  • Thank you @freedomn-m – ren Nov 18 '21 at 22:54

1 Answers1

2

A particularly interesting question with a more complex answer than I think you may have anticipated.

First off, I fear you have also forgotten to consider that timezones alone do not provide enough information to calculate day or night. You must also cross-reference that with a latitude reference because the duration of day and night vary across that.

A helpful lead, from another answer on Stack Overflow with similar credentials: https://stackoverflow.com/a/15044683/60318

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.

This would still need to be built into a function, but perhaps if you are clever with looking for gists on github you might find something helpful.

There is a sunrise/sunset calculator found here: https://gml.noaa.gov/grad/solcalc/sunrise.html

You can get an idea of cross-referencing the user's location with the timezones, and I think you will have a more complete solution.

dmanexe
  • 1,034
  • 4
  • 16
  • 40