1
#' Time zone
2
#'
3
#' Change the time zone, and restore it afterwards.
4
#'
5
#' `with_time_zone()` runs the code with the specified time zone and
6
#' resets it afterwards.
7
#'
8
#' `local_time_zone()` changes the time zone for the caller
9
#' execution environment.
10
#'
11
#' @template with
12
#' @param tz `[character(1)]` a valid time zone specification, note that
13
#'   time zone names might be platform dependent.
14
#'
15
#' @seealso [Sys.timezone()].
16
#' @export
17
#' @examples
18
#' Sys.time()
19
#' with_timezone("Europe/Paris", print(Sys.time()))
20
#' with_timezone("US/Pacific", print(Sys.time()))
21
#'
22
with_timezone <- function(tz, code) {
23 1
  old <- get0(".sys.timezone", baseenv(), mode = "character",
24 1
              inherits = FALSE, ifnotfound = NA_character_)
25 1
  on.exit(assign(".sys.timezone", old, envir = baseenv()), add = TRUE)
26 1
  assign(".sys.timezone", NA, envir = baseenv())
27 1
  with_envvar(c(TZ = tz), code)
28
}
29

30
#' @rdname with_timezone
31
#' @param .local_envir The environment to apply the change to.
32
#' @export
33
#' @examples
34
#' fun1 <- function() {
35
#'   local_timezone("CET")
36
#'   print(Sys.time())
37
#' }
38
#'
39
#' fun2 <- function() {
40
#'   local_timezone("US/Pacific")
41
#'   print(Sys.time())
42
#' }
43
#' Sys.time()
44
#' fun1()
45
#' fun2()
46
#' Sys.time()
47
local_timezone <- function(tz, .local_envir = parent.frame()) {
48 1
  old <- get0(".sys.timezone", baseenv(), mode = "character",
49 1
              inherits = FALSE, ifnotfound = NA_character_)
50 1
  withr::defer(
51 1
     assign(".sys.timezone", old, envir = baseenv()),
52 1
     envir = .local_envir)
53 1
  assign(".sys.timezone", NA, envir = baseenv())
54 1
  local_envvar(c(TZ = tz), .local_envir = .local_envir)
55
}

Read our documentation on viewing source code .

Loading