0

In PHP (since 5.2.0) I can write this code:

//$t is timestamp of day I want to look at
$tz=new DateTimeZone('America/New_York');
$transition = $tz->getTransitions($t,$t);
if(!$transition || count($transition)==0)throw new Exception("Bad timezone")
$offset=$transition[0]['offset'];   //This is seconds ahead of GMT.
      //I.e. -14400 in summer, -18000 in winter.

I nearly cried with joy when I discovered this class/idiom; but is there a way to do the same thing in R? Or do I have to resort to what I used to do in PHP, which was hard-code an array of summertime start/end dates for each timezone I need to consider?

(BTW, for more on the PHP code, see: How to tell if a timezone observes daylight saving at any time of the year? )

Community
  • 1
  • 1
Darren Cook
  • 27,837
  • 13
  • 117
  • 217
  • Thanks for the quick replies (they were the same; I gave the tick to Oscar simply as I was already using POSIXlt). I realized I could have been doing this in PHP all along too! – Darren Cook Jan 17 '12 at 00:26

2 Answers2

3

You can build two time objects, for the same date and time, one in the desired time zone, the other in GMT, and look at their difference.

# Winter: London uses GMT
> ISOdatetime(2012, 01, 01, 00, 00, 00, "Europe/London") - 
  ISOdatetime(2012, 01, 01, 00, 00, 00, "GMT")
Time difference of 0 secs

# Summer: London uses GMT+1
> ISOdatetime(2012, 08, 01, 00, 00, 00, "Europe/London") - 
  ISOdatetime(2012, 08, 01, 00, 00, 00, "GMT")
Time difference of -1 hours
Vincent Zoonekynd
  • 31,893
  • 5
  • 69
  • 78
3

With as.POSIXct and as.POSIXlt you can get this information. For example:

tz = 'Europe/Madrid'
d1 <- as.POSIXct('2010-01-01 12:00:00',  tz = tz)
as.POSIXlt(d1)$isdst ## 0 since it's not DST

If you need the difference from UTC:

d0 <- as.POSIXct(format(d1,  tz = 'UTC'),  tz = tz)
as.numeric(d1 - d0) ## 1 hour

The same for another day:

d2 <- as.POSIXct('2010-07-01 12:00:00',  tz = tz)
as.POSIXlt(d2)$isdst ## 1 since it is DST
d0 <- as.POSIXct(format1(d2,  tz = 'UTC'),  tz = tz)
as.numeric(d2 - d0) ## 2 hour
Oscar Perpiñán
  • 4,491
  • 17
  • 28