How can I round a date to the beginning / end of a quarter?

I need to take a vector of dates and for each date get the first day of the next quarter.

(Rather, round to the last day of the current quarter, find the first day of the next quarter and remove my plan from it)

lubridate will be round / ceiling up to several months but not quarters

The only solution I have found so far is to make a vector listing all the quarterly beginnings from 1970 to 2099, and then search it to find the minimum date after my date. It is clear that this greatly distorts and scales.

I need to indicate the year of the end of the year (although the year always starts on the 1st of the month)

eg.

 x = as.Date("2014-08-15") RoundToQuarterStart(x, yearStarts = "March") [1] "2014-09-01" 

From the moment the year begins on March 1 in this example, Q3 starts on September 1, which begins in the next quarter after the specified date. (or, which is the same, this date refers to Q2, which ends on August 31)

+7
date r rounding
source share
2 answers

The zoo package can help with many date related events, including the following:

 library(zoo) as.yearqtr("2014-08-15", format="%Y-%m-%d") ## [1] "2014 Q3" as.Date(as.yearqtr("2014-08-15", format="%Y-%m-%d")) ## [1] "2014-07-01" 

But this may not give you what you need (there are ways to extrapolate from these values).

The timeDate package has:

 timeFirstDayInQuarter(charvec, format = "%Y-%m-%d", zone = "", FinCenter = "") timeLastDayInQuarter(charvec, format = "%Y-%m-%d", zone = "", FinCenter = "") 

which may make it easier to use and configure to tune in to start the beginning of Q1.

+8
source share

For any time interval (Yearly, Quarterly, Monthly, Weekly), the following function gives the end date using the basic R functions (as.POSIXlt and as.Date):

 endDate <- function(date, interval) { date.lt <- as.POSIXlt(date) switch(interval, A = { date.lt$mon = 11 date.lt$mday=31 date=as.Date(date.lt) }, Q = { date.lt$mon = (date.lt$mon %/% 3 +1)*3 %% 12 date.lt$mday = 1 date.lt$year = date.lt$year + as.integer(date.lt$mon==0) date=as.Date(date.lt)-1 }, M = { date.lt$mon = (date.lt$mon+1) %% 12 date.lt$mday = 1 date.lt$year = date.lt$year + as.integer(date.lt$mon==0) date=as.Date(date.lt)-1 }, D = { date = as.Date(date) }, W = { date = as.Date(date)+6-date.lt$wday }, date = as.Date(date$lt) ) date } ### endDate (c("2003-05-21","1945-03-29), "M") # "2003-05-31" "1945-03-31" endDate (c("2003-05-21","1945-03-29), "M") #"2003-06-30" "1945-03-31" 
+1
source share

All Articles