datastorm-open / suncalc

R package for calculating sun/moon positions and phases, linked to suncalc.js
Other
43 stars 10 forks source link

Process datetimes in UTC (issue #2) #14

Closed mstrimas closed 10 months ago

mstrimas commented 1 year ago

Process datetimes in UTC rather than system time zone to ensure returned date times are not offset by 1 day in getSunlightTimes(). Addresses the issue reported at https://github.com/datastorm-open/suncalc/issues/2

bart1 commented 1 year ago

Maybe this also relates to #7?

mfidino commented 11 months ago

Adding in here another example of how the current setup does not work (and converting to UTC within getSunlightTimes) fixed the issue. This PR should get merged.

library(lubridate)
library(suncalc)

date = lubridate::ymd("2019-06-04")
lat = 14.96962
lon = 108.1707
tz = "Asia/Ho_Chi_Minh"
data = NULL

example <- suncalc::getSunlightTimes(
  date = lubridate::ymd("2019-06-04"),
  lat = 14.96962,
  lon = 108.1707,
  tz = "Asia/Ho_Chi_Minh"
)

t(
  example
)

              [,1]                 
date          "2019-06-04"         
lat           "14.96962"           
lon           "108.1707"           
solarNoon     "2019-06-05 11:47:08"
nadir         "2019-06-04 23:47:08"
sunrise       "2019-06-05 05:17:58"
sunset        "2019-06-05 18:16:18"
sunriseEnd    "2019-06-05 05:20:23"
sunsetStart   "2019-06-05 18:13:53"
dawn          "2019-06-05 04:54:29"
dusk          "2019-06-05 18:39:47"
nauticalDawn  "2019-06-05 04:26:46"
nauticalDusk  "2019-06-05 19:07:30"
nightEnd      "2019-06-05 03:58:25"
night         "2019-06-05 19:35:51"
goldenHourEnd "2019-06-05 05:48:37"
goldenHour    "2019-06-05 17:45:39"
bthieurmel commented 10 months ago

This path / fix not always working...

See this more complete example :

library(lutz)
library(suncalc)
library(tidyverse)

# default system time zone
Sys.timezone()
#> "America/Los_Angeles"

# example locations along the equator at various longitudes

data_grid <- expand.grid(lat = seq(-90, 90, by = 10), 
                         lon = seq(-180, 180, by = 20))

data_grid$date <- as.Date("2023-06-01")

data <- data_grid %>% 
  mutate(tz = tz_lookup_coords(lat = lat, lon = lon,
                               method = "accurate", warn = FALSE)) 

data$tz <- sapply(data$tz, function(x) strsplit(x, ";")[[1]][1])
# solar noon
res <- data %>% 
  mutate(solar_noon = pmap(list(date = date, lat = lat, lon = lon, tz = tz),
                           getSunlightTimes,
                           keep = "solarNoon") %>% 
           map("solarNoon") %>% 
           map_chr(as.character))

I'm looking to a fully working solution.