Format vector values to time values using one of five presets. Input can be
in the form of POSIXt
(i.e., date-times), character
(must be in the ISO
8601 forms of HH:MM:SS
or YYYY-MM-DD HH:MM:SS
), or Date
(which always
results in the formatting of 00:00:00
).
We can simply apply a preset time style to format the times. The following
time styles are available for use (all using the input time of 14:35:00
in
the example output times):
"hms"
: 14:35:00
"hm"
: 14:35
"hms_p"
: 2:35:00 PM
"hm_p"
: 2:35 PM
"h_p"
: 2 PM
We can use the info_time_style()
function for a useful reference on all of
the possible inputs to time_style
.
vec_fmt_time(
x,
time_style = 2,
pattern = "{x}",
output = c("auto", "plain", "html", "latex", "rtf", "word")
)
A character vector.
A numeric vector.
The time style to use. Supply a number (from 1
to 5
)
that corresponds to the preferred time style, or, provide a named time
style ("hms"
, "hms_p"
, "h_p"
, etc.). Use info_time_style()
to see
the different numbered and named time presets.
A formatting pattern that allows for decoration of the
formatted value. The value itself is represented by {x}
and all other
characters are taken to be string literals.
The output style of the resulting character vector. This can
either be "auto"
(the default), "plain"
, "html"
, "latex"
, "rtf"
,
or "word"
. In knitr rendering (i.e., Quarto or R Markdown), the
"auto"
option will choose the correct output
value
Let's create a character vector of datetime values in the ISO-8601 format for the next few examples:
str_vals <- c("2022-06-13 18:36", "2019-01-25 01:08", NA)
Using vec_fmt_time()
with the default options will create a character
vector of formatted times. Any NA
values remain as NA
values. The
rendering context will be autodetected unless specified in the output
argument (here, it is of the "plain"
output type).
vec_fmt_time(str_vals)
#> [1] "18:36" "01:08" NA
We can change the formatting style by choosing a number from 1
to 5
:
vec_fmt_time(str_vals, time_style = 4)
#> [1] "6:36 PM" "1:08 AM" NA
We can always use info_time_style()
to call up an info table that serves as
a handy reference to all of the time styles.
As a last example, one can wrap the time values in a pattern with the
pattern
argument. Note here that NA
values won't have the pattern
applied.
vec_fmt_time(str_vals, time_style = 4, pattern = "Time: {x}")
#> [1] "Time: 6:36 PM" "Time: 1:08 AM" NA
14-11
Other vector formatting functions:
vec_fmt_bytes()
,
vec_fmt_currency()
,
vec_fmt_datetime()
,
vec_fmt_date()
,
vec_fmt_duration()
,
vec_fmt_engineering()
,
vec_fmt_fraction()
,
vec_fmt_integer()
,
vec_fmt_markdown()
,
vec_fmt_number()
,
vec_fmt_partsper()
,
vec_fmt_percent()
,
vec_fmt_scientific()