diff --git a/NEWS.md b/NEWS.md index b0e8bb1e..f2c34b4f 100644 --- a/NEWS.md +++ b/NEWS.md @@ -1,5 +1,7 @@ # scales 0.5.0.9000 +* New function `time_format()` formats `POSIXt` and `hms` objects (@dpseidel, #88). + * `rescale_mid()` now properly handles NAs (@foo-bar-baz-qux, #104). * `log_breaks()` returns integer multiples of integer powers of base when finer diff --git a/R/trans-date.r b/R/trans-date.r index 0d3a65db..e54c5039 100644 --- a/R/trans-date.r +++ b/R/trans-date.r @@ -34,7 +34,6 @@ from_date <- function(x) { #' t$format(t$breaks(range(hours))) time_trans <- function(tz = NULL) { force(tz) - to_time <- function(x) { structure(x, class = c("POSIXt", "POSIXct"), tzone = tz) } @@ -127,3 +126,27 @@ date_format <- function(format = "%Y-%m-%d", tz = "UTC") { force_all(format, tz) function(x) format(x, format, tz = tz) } + +#' Formatted times. +#' +#' @param format Time format using standard POSIX specification. See +#' [strptime()] for possible formats. +#' @param tz a time zone name, see [timezones()]. Defaults +#' to UTC +#' @export +time_format <- function(format = "%H:%M:%S", tz = "UTC") { + force_all(format, tz) + function(x) { + if (inherits(x, "POSIXt")) { + format(x, format = format, tz = tz) + } else if (inherits(x, "difftime")) { + format(as.POSIXct(x), format = format, tz = tz) + } else { + stop( + "time_format can't be used with objects of class ", paste(class(x), collapse = "/"), + ".", + call. = FALSE + ) + } + } +} diff --git a/tests/testthat/test-trans-date.r b/tests/testthat/test-trans-date.r index 3b1f9d7e..e0f7df83 100644 --- a/tests/testthat/test-trans-date.r +++ b/tests/testthat/test-trans-date.r @@ -40,3 +40,10 @@ test_that("tz arugment overrules default time zone", { expect_equal(tz(x), "GMT") expect_equal(tz2(x), "GMT") }) + +test_that("time_format formats hms objects", { + expect_equal(time_format()(a_time), "11:30:00") + skip_if_not_installed("hms") + expect_equal(time_format()(hms::as.hms(a_time, tz = tz(a_time))), "11:30:00") + expect_equal(time_format(format = "%H")(hms::as.hms(a_time, tz = tz(a_time))), "11") +})