Calculating Time of Year with R's lubridate Package

In order to find the time of year, we can use lubridate::year and lubridate::quarter, which return the number of years and quarters between two dates, respectively.

library(lubridate)

toy_df$years <- as.numeric(as.period(interval(start = birthdate, end = givendate))$year)
toy_df$quarters <- quarter(as.period(interval(start = birthdate, end = givendate)))

# Print the resulting data frame
toy_df

    birthdate  givendate years quarters
1  1978-12-30 2015-12-31     37       4
2  1978-12-31 2015-12-31     36       4
3  1979-01-01 2015-12-31     36       1
4  1962-12-30 2015-12-31     53       4
5  1962-12-31 2015-12-31     52       4
6  1963-01-01 2015-12-31     52       1
7  2000-06-16 2050-06-17     50       2
8  2000-06-17 2050-06-17     49       2
9  2000-06-18 2050-06-17     49       2
10 2007-03-18 2008-03-19      1       1
11 2007-03-19 2008-03-19      1       1
12 2007-03-20 2008-03-19      0       1
13 1968-02-29 2015-02-28     47       4
14 1968-02-29 2015-03-01     47       1
15 1968-02-29 2015-03-02     47       2

We can also calculate the quarter of the year using lubridate::quarter which returns a value between 1 and 4, where:

  • Quarter 1: January - March
  • Quarter 2: April - June
  • Quarter 3: July - September
  • Quarter 4: October - December

Last modified on 2024-10-28