
Convert timestamps to UTC while respecting local timezones
Source:R/timezone_helpers.R
with_localtime.RdThis functions takes a vector of timestamps and a corresponding vector of time zones and converts it to "localtime" at UTC. If you have a vector of timestamps with varying time zones, you cannot represent them in a single vector with their own time zone. To this end, this function converts each timestamp to its local time, and then force UTC as a time zone for all values.
Arguments
- x
A vector of timestamps, either as
lubridate::POSIXctor character strings.- tz
A character vector of timezones corresponding to each element in
x. If all elements share the same timezone, a single value can be supplied.
Value
A lubridate::POSIXct vector in UTC.
Examples
# Single timezone
x <- as.POSIXct("2025-05-10 12:00:00", tz = "UTC")
with_localtime(x, "Europe/Brussels")
#> [1] "2025-05-10 14:00:00 UTC"
# Multiple timezones
times <- as.POSIXct(c("2025-05-10 12:00:00", "2025-05-10 12:00:00"), tz = "UTC")
tzs <- c("Europe/Brussels", "America/New_York")
# Times not appear to be in UTC, but the values are in their local time zone.
with_localtime(times, tzs)
#> [1] "2025-05-10 14:00:00 UTC" "2025-05-10 08:00:00 UTC"