File: asJSON.POSIXt.R

package info (click to toggle)
r-cran-jsonlite 1.6%2Bdfsg-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 1,304 kB
  • sloc: ansic: 3,789; sh: 9; makefile: 2
file content (41 lines) | stat: -rw-r--r-- 1,173 bytes parent folder | download | duplicates (3)
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
setMethod("asJSON", "POSIXt", function(x, POSIXt = c("string", "ISO8601", "epoch",
  "mongo"), UTC = FALSE, digits, time_format = NULL, always_decimal = FALSE, ...) {
  # note: UTC argument doesn't seem to be working consistently maybe use ?format
  # instead of ?as.character

  # Validate
  POSIXt <- match.arg(POSIXt)

  # Encode based on a schema
  if (POSIXt == "mongo") {
    if (inherits(x, "POSIXlt")) {
      x <- as.POSIXct(x)
    }
    df <- data.frame("$date" = floor(unclass(x) * 1000), check.names = FALSE)
    if(inherits(x, "scalar"))
      class(df) <- c("scalar", class(df))
    return(asJSON(df, digits = NA, always_decimal = FALSE, ...))
  }

  # Epoch millis
  if (POSIXt == "epoch") {
    return(asJSON(floor(unclass(as.POSIXct(x)) * 1000), digits = digits, always_decimal = FALSE, ...))
  }

  # Strings
  if(is.null(time_format)){
    time_format <- if(POSIXt == "string"){
      ""
    } else if(isTRUE(UTC)){
      "%Y-%m-%dT%H:%M:%SZ"
    } else {
      "%Y-%m-%dT%H:%M:%S"
    }
  }

  if (isTRUE(UTC)) {
    asJSON(as.character(x, format = time_format, tz = "UTC"), ...)
  } else {
    asJSON(as.character(x, format = time_format), ...)
  }
})