Skip to content

Commit

Permalink
feat: get the number of days in a month
Browse files Browse the repository at this point in the history
  • Loading branch information
ahasverus committed Mar 29, 2024
1 parent e555497 commit a15264e
Show file tree
Hide file tree
Showing 4 changed files with 107 additions and 0 deletions.
1 change: 1 addition & 0 deletions NAMESPACE
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# Generated by roxygen2: do not edit by hand

export(number_of_days)
importFrom(grDevices,dev.off)
importFrom(grDevices,pdf)
importFrom(graphics,par)
Expand Down
67 changes: 67 additions & 0 deletions R/number_of_days.R
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
#' Return the number of days in a month for a given year
#'
#' @param date either a `character` or a `Date` of length 1. See examples below.
#'
#' @param format a `character` of length 1. Used to specify the format of the
#' date. Default is `"%Y-%m-%d"` (i.e. 2024-12-25). See examples below.
#'
#' @return An `integer` corresponding to the number of days in the month for
#' the specified year.
#'
#' @export
#'
#' @examples
#' ## Default ----
#' number_of_days("2024-02-01")
#'
#' ## Day doesn't matter ----
#' number_of_days("2024-02-23")
#'
#' ## Year matters ----
#' number_of_days("2023-02-23")
#'
#' ## Change the format ----
#' number_of_days("2024/02/23", format = "%Y/%m/%d")
#'
#' ## French format ----
#' number_of_days("23/02/2024", format = "%d/%m/%Y")

number_of_days <- function(date, format = "%Y-%m-%d") {

if (missing(date)) {
stop("Argument 'date' is required", call. = FALSE)
}

if (!is.character(date) && !inherits(date, "Date")) {
stop("Argument 'date' must be either a character or a Date", call. = FALSE)
}

if (length(date) != 1) {
stop("Argument 'date' must be of length 1", call. = FALSE)
}

if (nchar(as.character(date)) != 10) {
stop("Wrong 'date'. Year must have 4 characters (e.g. 2024), month 2 ",
"characters (e.g. 01), and day 2 characters (e.g. 01)", call. = FALSE)
}

if (is.character(date)) {
date <- as.Date(date, format = format)
}


if (is.na(date)) {
stop("Error in converting 'date'. Please use the argument 'format' to ",
"specify the appropriate format. See '?strptime' for further ",
"information", call. = FALSE)
}

month <- format(date, format = "%m")

while (format(date, format = "%m") == month) {

date <- date + 1
}

as.integer(format(date - 1, format = "%d"))
}
2 changes: 2 additions & 0 deletions man/calendar-package.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

37 changes: 37 additions & 0 deletions man/number_of_days.Rd

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

0 comments on commit a15264e

Please sign in to comment.