r-lib / withr
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
  reset_timezone()
24 1
  with_envvar(c(TZ = tz), code)
25
}
26

27
#' @rdname with_timezone
28
#' @param .local_envir The environment to apply the change to.
29
#' @export
30
#' @examples
31
#' fun1 <- function() {
32
#'   local_timezone("CET")
33
#'   print(Sys.time())
34
#' }
35
#'
36
#' fun2 <- function() {
37
#'   local_timezone("US/Pacific")
38
#'   print(Sys.time())
39
#' }
40
#' Sys.time()
41
#' fun1()
42
#' fun2()
43
#' Sys.time()
44
local_timezone <- function(tz, .local_envir = parent.frame()) {
45 1
  reset_timezone(envir = .local_envir)
46 1
  local_envvar(c(TZ = tz), .local_envir = .local_envir)
47
}
48

49
reset_timezone <- function(envir = parent.frame()) {
50 1
  base_env <- baseenv()
51 1
  old <- get0(".sys.timezone", base_env, mode = "character",
52 1
              inherits = FALSE, ifnotfound = NA_character_)
53 1
  is_locked <- bindingIsLocked(".sys.timezone", env = base_env)
54 1
  if (is_locked) {
55 0
    base_env$unlockBinding(".sys.timezone", env = base_env)
56
  }
57 1
  defer({
58 1
    assign(".sys.timezone", old, envir = base_env)
59 1
    if (is_locked) {
60 0
      lockBinding(".sys.timezone", env = base_env)
61
    }
62 1
  }, envir = envir)
63 1
  assign(".sys.timezone", NA_character_, envir = base_env)
64
}

Read our documentation on viewing source code .

Loading