Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

date

rounding

r

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

(Or rather, to round to the last day of the current quarter, find the first day of the next quarter and take on off is my plan)

lubridate will round/ceiling to months, but not quarters

Only solution I've found so far is to make a vector listing all the quarter starts from 1970 to 2099 and then search through that to find the minimum date after my date. Clearly, this vectorises and scales badly.

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

E.g.

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

Since year starts on 1st March in this example, then Q3 starts 1st September, which is the next quarter start after the given date. (or equivalently this date belongs to Q2 which ends on 31st August)

like image 636
Corvus Avatar asked Apr 13 '14 17:04

Corvus


People also ask

How do you round a date to the nearest quarter?

It would be quarters based on a standard calendar year. So if the date with six months added is 08/17/2018, it needs to then show the next quarter date of 10/01/2018. The final results for the quarters should be one of these: 1/1/18, 4/1/18, 7/1/18, 10/1/18 or go into the next year if necessary.

How do you convert a date to a quarter?

The MONTH(B3) part of the formula takes the date and returns the numerical month value of the date, so for example MONTH("2014-07-15") would return a value of 7. We then use ROUNDUP(Month/3,0) to get the numerical value of the quarter, 7/3 = 2.333 and rounding this up we get 3 (the third quarter).

How do you find a quarter start date and end date?

3rd quarter of an year includes the months July, August and September, so start date of the quarter is the 1st day in July and end date is the last day of September. If you have February or March for example the start date will be 01 Jan 2016 and end date will be 31 Mar 2016. It is that simple.


1 Answers

The zoo package can help for many things date-related including this:

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, that might not get you what you need (there are ways to extrapolate from those values).

The timeDate package has:

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

which might make it easer to use and tweak to adjust for different Q1 start origins.

like image 127
hrbrmstr Avatar answered Oct 17 '22 07:10

hrbrmstr