Browse files

Added richierocks' days_in_month function. Great idea and thanks for …

…the tests! Fixes #118.
  • Loading branch information...
1 parent e9dc00c commit b400df55cd587d7282eccc0004674ff2b4e8f7a8 @garrettgman garrettgman committed Oct 1, 2012
Showing with 72 additions and 1 deletion.
  1. +1 −0 NAMESPACE
  2. +22 −1 R/accessors-month.r
  3. +30 −0 inst/tests/test-accessors.R
  4. +19 −0 man/days_in_month.Rd
View
1 NAMESPACE
@@ -71,6 +71,7 @@ export(as.period)
export(ceiling_date)
export(day)
export(days)
+export(days_in_month)
export(ddays)
export(decimal_date)
export(dhours)
View
23 R/accessors-month.r
@@ -61,4 +61,25 @@ month.numeric <- function(x, label = FALSE, abbr = TRUE) {
"june", "july", "august", "september", "october", "november", "december"))
}
x <- x + months(value - month(x))
- }
+ }
+
+#' Get the number of days in the month of a date-time.
+#'
+#' Date-time must be a POSIXct, POSIXlt, Date, chron, yearmon, yearqtr,
+#' zoo, zooreg, timeDate, xts, its, ti, jul, timeSeries, and fts objects.
+#'
+#' @export days_in_month
+#' @param x a date-time object
+#' @return An integer of the number of days in the month component of the date-time object.
+days_in_month <- function(x) {
+ month_x <- month(x, label = TRUE)
+ N_DAYS <- c(
+ Jan = 31L, Feb = 28L, Mar = 31L,
+ Apr = 30L, May = 31L, Jun = 30L,
+ Jul = 31L, Aug = 31L, Sep = 30L,
+ Oct = 31L, Nov = 30L, Dec = 31L
+ )
+ n_days <- N_DAYS[month_x]
+ n_days[month_x == "Feb" & leap_year(x)] <- 29L
+ n_days
+}
View
30 inst/tests/test-accessors.R
@@ -156,3 +156,33 @@ test_that("accessors handle vectors",{
expect_that(tz(date), matches("UTC"))
})
+
+context("test days_in_month")
+
+test_that(
+ "days in month works for non leap years",
+{
+ x <- seq(ymd("2011-01-01"), ymd("2011-12-01"), "1 month")
+ expected <- c(
+ Jan = 31L, Feb = 28L, Mar = 31L,
+ Apr = 30L, May = 31L, Jun = 30L,
+ Jul = 31L, Aug = 31L, Sep = 30L,
+ Oct = 31L, Nov = 30L, Dec = 31L
+ )
+ expect_that(days_in_month(x), equals(expected))
+}
+)
+
+test_that(
+ "days in month works for leap years",
+{
+ x <- seq(ymd("2012-01-01"), ymd("2012-12-01"), "1 month")
+ expected <- c(
+ Jan = 31L, Feb = 29L, Mar = 31L,
+ Apr = 30L, May = 31L, Jun = 30L,
+ Jul = 31L, Aug = 31L, Sep = 30L,
+ Oct = 31L, Nov = 30L, Dec = 31L
+ )
+ expect_that(days_in_month(x), equals(expected))
+}
+)
View
19 man/days_in_month.Rd
@@ -0,0 +1,19 @@
+\name{days_in_month}
+\alias{days_in_month}
+\title{Get the number of days in the month of a date-time.}
+\usage{
+ days_in_month(x)
+}
+\arguments{
+ \item{x}{a date-time object}
+}
+\value{
+ An integer of the number of days in the month component
+ of the date-time object.
+}
+\description{
+ Date-time must be a POSIXct, POSIXlt, Date, chron,
+ yearmon, yearqtr, zoo, zooreg, timeDate, xts, its, ti,
+ jul, timeSeries, and fts objects.
+}
+

0 comments on commit b400df5

Please sign in to comment.