| 1 |
#' Time zone |
| 2 |
#' |
| 3 |
#' Change the time zone, and restore it afterwards. |
| 4 |
#' |
| 5 |
#' `with_timezone()` runs the code with the specified time zone and |
| 6 |
#' resets it afterwards. |
| 7 |
#' |
| 8 |
#' `local_timezone()` 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("America/Los_Angeles", print(Sys.time())) |
| 21 |
#' |
| 22 |
with_timezone <- function(tz, code) { |
| 23 |
reset_timezone() |
| 24 |
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("America/Los_Angeles") |
| 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 |
reset_timezone(envir = .local_envir) |
| 46 |
local_envvar(c(TZ = tz), .local_envir = .local_envir) |
| 47 |
} |
| 48 |
|
| 49 |
reset_timezone <- function(envir = parent.frame()) { |
| 50 |
base_env <- baseenv() |
| 51 |
old <- get0( |
| 52 |
".sys.timezone", |
| 53 |
base_env, |
| 54 |
mode = "character", |
| 55 |
inherits = FALSE, |
| 56 |
ifnotfound = NA_character_ |
| 57 |
) |
| 58 |
is_locked <- bindingIsLocked(".sys.timezone", env = base_env) |
| 59 |
if (is_locked) { |
| 60 |
base_env$unlockBinding(".sys.timezone", env = base_env) |
| 61 |
} |
| 62 |
defer( |
| 63 |
{ |
| 64 |
assign(".sys.timezone", old, envir = base_env) |
| 65 |
if (is_locked) { |
| 66 |
lockBinding(".sys.timezone", env = base_env) |
| 67 |
} |
| 68 |
}, |
| 69 |
envir = envir |
| 70 |
) |
| 71 |
assign(".sys.timezone", NA_character_, envir = base_env) |
| 72 |
} |