newbie
newbie

Reputation: 767

Converting UTC time to local standard time in R

I am trying to convert UTC time to local standard time. I have found many functions which convert to Local Daylight Time, but I was not successful in getting the standard time. Right now, I have the following code which converts to local daylight time at my specific timezone:

pb.date <- as.POSIXct(date,tz="UTC")
format(pb.date, tz="timeZone",usetz=TRUE)

I would appreciate any help.

Upvotes: 11

Views: 40150

Answers (2)

Josh Pachner
Josh Pachner

Reputation: 511

I know this question has an accepted answer, but in case anyone comes along and this can help. I needed a function to convert UTC times to MTN time (Server is in UTC, we operate in MTN). Not sure why, but needed to force it to UTC/GMT first and the convert it to MTN. However it does work

mtn_ts = function(utcTime){
  library(lubridate)
  toTz = "us/mountain"
  utcTime = force_tz(utcTime,tzone= 'GMT')
  dt = as.POSIXct(format(utcTime,tz = toTz,origin ='GMT', usetz=TRUE))
  dt = force_tz(dt,tzone= toTz)
  return(dt)
}
mtn_ts(as.POSIXct("2021-09-27 14:48:51.000000000"))

Upvotes: 0

IRTFM
IRTFM

Reputation: 263342

First, POSIXct date-times are always UCT internally. The print.POSIXt and format.POSIXt methods will appropriately make the TZ shift on output from their internal representations:

pb.date <- as.POSIXct(Sys.Date())
Sys.Date()
#[1] "2015-07-09"

So that was midnight of the current date in Greenwich:

format(pb.date, tz="America/Los_Angeles",usetz=TRUE)
#[1] "2015-07-08 17:00:00 PDT"

When it's midnight in Greenwich, it's 5PM Daylight Time in the previous day on the Left Coast of the US. You need to use the correct character values for your TZ (and your OS) both of which at the moment are unspecified.

The US Pacific timezone is 8 hours behind GMT (in winter months) so you can use a timezone that is Standard/Daylight-agnostic:

> format(pb.date,usetz=TRUE, tz="Etc/GMT+8")
[1] "2015-07-08 16:00:00 GMT+8"

(Notice the reversal of + with "behind" and - with "ahead".)

Upvotes: 11

Related Questions