Given I have time ranges with a start and an end date, I can easily determine if a specific date falls in this time range. How can we determine if a specific month/day combination lies in a time range, independent from its year.
Example
Given I would like to know whether any first of July (07-01
) lies in a time range.
2020-01-30 - 2020-06-15 --> NO
2020-06-16 - 2021-03-20 --> YES
2013-04-26 - 2019-02-13 --> YES (multiple)
R Code Example
# set seed for sampling
set.seed(1)
# number of time ranges
cases <- 10
# time gaps in days
gaps <- sort(sample(x = 1:5000, size = cases, replace = TRUE))
# data frame with time ranges
df <- data.frame(dates_start = rev(Sys.Date() - gaps[2:cases] + 1),
dates_end = rev(Sys.Date() - gaps[1:(cases-1)]))
df
#> dates_start dates_end
#> 1 2009-06-26 2010-01-19
#> 2 2010-01-20 2011-06-05
#> 3 2011-06-06 2011-06-20
#> 4 2011-06-21 2013-04-21
#> 5 2013-04-22 2016-02-17
#> 6 2016-02-18 2016-08-05
#> 7 2016-08-06 2018-05-11
#> 8 2018-05-12 2019-10-09
#> 9 2019-10-10 2021-10-25
# Is specific date in date range
df$date_in_range <- df$dates_start <= lubridate::ymd("2019-07-01") &
lubridate::ymd("2019-07-01") < df$dates_end
# specific day of a month in date range
# pseudo code
data.table::between(x = month_day("07-01"),
lower = dates_start,
upper = dates_end)
#> Error in month_day("07-01"): could not find function "month_day"
# expected output
df$monthday_in_range <- c(T, T, F, T, T, T, T, T, T)
df
#> dates_start dates_end date_in_range monthday_in_range
#> 1 2009-06-26 2010-01-19 FALSE TRUE
#> 2 2010-01-20 2011-06-05 FALSE TRUE
#> 3 2011-06-06 2011-06-20 FALSE FALSE
#> 4 2011-06-21 2013-04-21 FALSE TRUE
#> 5 2013-04-22 2016-02-17 FALSE TRUE
#> 6 2016-02-18 2016-08-05 FALSE TRUE
#> 7 2016-08-06 2018-05-11 FALSE TRUE
#> 8 2018-05-12 2019-10-09 TRUE TRUE
#> 9 2019-10-10 2021-10-25 FALSE TRUE