Home > other >  How to get the start date of the astronomical season from a date
How to get the start date of the astronomical season from a date

Time:07-27

I tried using the lubridate::floor_date function to get the first date of the season in which my input date is, for ex.:

x <- ymd_hms("2008-08-03 12:01:59.23")

this date is in the summer of 2008, so starting 21-06-2008 and ending 20-09-2008. According to this i expected that by running this

lubridate::floor_date(x, "season")

i would get this

21-06-2008

but instead i get this

"2008-06-01 UTC"

which is not the beginning of the summer of 2008.

Am I using the wrong function, or is there another way to achieve what I'm trying to get ?

enter image description here

CodePudding user response:

As you are using lubridate then you can create a function using floor_date().

astronomical_floor <- function(x) {
    stopifnot(
        (is(x, "Date") | is(x, "POSIXct") | is(x, "POSIXt"))
    )

    astronomical_floor <- x |>
        floor_date("season") |>
        format("%Y-%m-21") |>
        ymd()

    # Make sure floor not greater than date
    # e.g. 2022-06-05 should return 2022-03-21
    # not 2022-06-21
    if (astronomical_floor > x) {
        astronomical_floor <- floor_date(
            x %m % months(-1)
        ) |>
            floor_date("season") |>
            format("%Y-%m-21") |>
            ymd()
    }

    return(astronomical_floor)
}


x <- ymd_hms("2008-08-03 12:01:59.23")
astronomical_floor(x) # "2008-06-21"
astronomical_floor(as.Date("2020-01-01")) # "2019-12-21"
astronomical_floor(x = ymd("2022-06-05")) # "2022-03-21"
  • Related