/
time-zones.r
58 lines (52 loc) · 2.42 KB
/
time-zones.r
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
#' Get date-time in a different time zone
#'
#' with_tz returns a date-time as it would appear in a different time zone.
#' The actual moment of time measured does not change, just the time zone it is
#' measured in. with_tz defaults to the Universal Coordinated time zone (UTC) when an unrecognized time zone is inputted. See \code{\link{Sys.timezone}} for more information on how R recognizes time zones.
#'
#' @export with_tz
#' @param time a POSIXct, POSIXlt, Date, or chron date-time object.
#' @param tzone a character string containing the time zone to convert to. R must recognize the name
#' contained in the string as a time zone on your system.
#' @return a POSIXct object in the updated time zone
#' @keywords chron manip
#' @seealso \code{\link{force_tz}}
#' @examples
#' x <- as.POSIXct("2009-08-07 00:00:01", tz = "America/New_york")
#' with_tz(x, "GMT")
#' # "2009-08-07 04:00:01 GMT"
with_tz <- function (time, tzone = ""){
if (is.POSIXlt(time)) new <- as.POSIXct(time)
else new <- time
new <- as.POSIXlt(new, tz = tzone)
reclass_date(new, time)
}
#' Replace time zone to create new date-time
#'
#' force_tz returns a the date-time that has the same clock time as x in the new time zone.
#' Although the new date-time has the same clock time (e.g. the
#' same values in the year, month, days, etc. elements) it is a
#' different moment of time than the input date-time. force_tz defaults to the Universal Coordinated time zone (UTC) when an unrecognized time zone is inputted. See \code{\link{Sys.timezone}} for more information on how R recognizes time zones.
#'
#' @export force_tz
#'
#' @param time a POSIXct, POSIXlt, Date, or chron date-time object.
#' @param tzone a character string containing the time zone to convert to. R must recognize the name
#' contained in the string as a time zone on your system.
#' @return a POSIXct object in the updated time zone
#' @keywords chron manip
#' @seealso \code{\link{with_tz}}
#' @examples
#' x <- as.POSIXct("2009-08-07 00:00:01", tz = "America/New_york")
#' force_tz(x, "GMT")
#' # "2009-08-07 00:00:01 GMT"
force_tz <- function(time, tzone = ""){
x <- as.POSIXlt(time)
if(is.null(tzone)) tzone <- ""
new <- ISOdatetime(year(x), month(x), mday(x), hour(x),
minute(x), second(x), tzone)
missing_hour <- hour(with_tz(new, tzone)) != hour(time)
new[missing_hour] <- NA
reclass_date(new, time)
}
# Note: alternative method? as.POSIXlt(format(as.POSIXct(x)), tz = tz)