Skip to content

Change the time zone, and restore it afterwards.

Usage

with_timezone(tz, code)

local_timezone(tz, .local_envir = parent.frame())

Arguments

tz

[character(1)] a valid time zone specification, note that time zone names might be platform dependent.

code

[any]
Code to execute in the temporary environment

.local_envir

The environment to apply the change to.

Value

[any]
The results of the evaluation of the codeargument.

Details

with_time_zone() runs the code with the specified time zone and resets it afterwards.

local_time_zone() changes the time zone for the caller execution environment.

See also

withr for examples

Sys.timezone().

Examples

Sys.time()
#> [1] "2022-03-03 22:18:10 UTC"
with_timezone("Europe/Paris", print(Sys.time()))
#> [1] "2022-03-03 23:18:10 CET"
with_timezone("US/Pacific", print(Sys.time()))
#> [1] "2022-03-03 14:18:10 PST"

fun1 <- function() {
  local_timezone("CET")
  print(Sys.time())
}

fun2 <- function() {
  local_timezone("US/Pacific")
  print(Sys.time())
}
Sys.time()
#> [1] "2022-03-03 22:18:10 UTC"
fun1()
#> [1] "2022-03-03 23:18:10 CET"
fun2()
#> [1] "2022-03-03 14:18:10 PST"
Sys.time()
#> [1] "2022-03-03 22:18:10 UTC"