I want to get current time in UTC/GMT using base R. Sys.time()
gives me time in my local time zone. I know using lubridate
I can do lubridate::now(tz = 'UTC')
to get what I want but I want to do this using base R since I want to have as minimum dependency as possible.
I have tried to look around on SO for the answer but have not found any post answering my question.
One idea I had was to add/subtract number of hours my local time zone is behind/ahead of GMT respectively but I cannot use it since the code would be deployed on a server where I don't know what would be the local time zone. Also this seems to be hacky and not robust.
Is there a robust way of doing this?
CodePudding user response:
One of the option might be:
Sys.setenv(TZ="GMT")
CodePudding user response:
You can set the attribute of the date/time object after you create it. For example
now_utc <- function() {
now <- Sys.time()
attr(now, "tzone") <- "UTC"
now
}
now_utc()
# [1] "2022-08-23 13:34:36 UTC"