forked from rstudio/blastula
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathadd_readable_time.R
66 lines (56 loc) · 1.97 KB
/
add_readable_time.R
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
#' Create a string with a more readable date/time
#'
#' Add a nicely-formatted date/time string inside the body of the email with
#' this helper function. We can provide a `POSIXct` date-time object or use the
#' current date/time/tz (based on the user's locale information at the time of
#' the function call). There are options to specify whether the date, time, and
#' time zone parts are to be included.
#'
#' @param time The `POSIXct` time to use, and to make more readable for email
#' recipients. If a `time` is not provided (the default), the current system
#' time will be used.
#' @param use_date,use_time,use_tz Logical value that indicate whether to
#' include the date, time, or time zone components.
#' @return A character object that can be placed inside any message component
#' message wherever the function is called.
#'
#' @export
add_readable_time <- function(time = NULL,
use_date = TRUE,
use_time = TRUE,
use_tz = TRUE) {
if (is.null(time)) {
time <- Sys.time()
} else if (!inherits(time, "POSIXct")) {
stop("The `time` value must be a POSIXct date-time value.", call. = FALSE)
}
if (isTRUE(use_date)) {
current_date <-
paste0(
format(time, "%A, %B "),
format(time, "%d") %>% as.numeric(),
", ",
format(time, "%Y"))
} else {
current_date <- ""
}
if (isTRUE(use_time)) {
current_time <-
paste0(
gsub(" ", "", format(time, "%l:%M")),
toupper(format(time, " %p")))
if (isTRUE(use_date)) {
current_time <- paste0(" at ", current_time)
}
} else {
current_time <- ""
}
if (isTRUE(use_tz) && (isTRUE(use_date) || isTRUE(use_time))) {
current_tz <- format(time, " (%Z)")
} else if (isTRUE(use_tz) && (use_date == FALSE && use_time == FALSE)) {
current_tz <- format(time, "%Z")
} else {
current_tz <- ""
}
paste0(current_date, current_time, current_tz)
}