Search code examples
rdatetimeshinydate-range

Pass datetime with time-zone objects to date-range input in shiny dashboard


I have a shiny dashboard below with a dateRange() input in which I want to pass datetimes with timezone. But when I try to convert my datetime objects to dates after having converted them to factors I get NAs. How could I proceed?

require(lubridate)
require(dplyr)

df = data.frame(timestring = c("2015-12-12 13:34:56", "2015-12-14 16:23:32"),
                localzone = c("America/Los_Angeles", "America/New_York"), stringsAsFactors = F)

df$moment = as.POSIXct(df$timestring, format="%Y-%m-%d %H:%M:%S", tz="UTC")

df = df %>% rowwise() %>% mutate(localtime = force_tz(moment, localzone))

df

df$localtime <- factor(df$localtime)

df$localtime<- as.Date(df$localtime, format = "%Y/%m/%d")

## app.R ##
library(shiny)
library(shinydashboard)

ui <- dashboardPage(
  dashboardHeader(),
  dashboardSidebar(
    dateRangeInput('dateRange',
                   label = 'Date range input: yyyy-mm-dd',
                   start = df$localtime - 2, end = df$localtime + 2
    )
  ),
  dashboardBody()
)

server <- function(input, output) {


}

shinyApp(ui, server)

Solution

  • You don't want to convert a date object to factor. I deleted the factor() line and it worked fine. Also, I guess you want the user to choose the location for time zone, since you have two items in your dataframe but start, end only accept one. I added a location selector.

    require(lubridate)
    require(dplyr)
    
    df = data.frame(timestring = c("2015-12-12 13:34:56", "2015-12-14 16:23:32"),
                    localzone = c("America/Los_Angeles", "America/New_York"), stringsAsFactors = F)
    
    df$moment = as.POSIXct(df$timestring, format="%Y-%m-%d %H:%M:%S", tz="UTC")
    
    df = df %>% rowwise() %>% mutate(localtime = force_tz(moment, localzone))
    
    df$localtime = as.Date(df$localtime, format = "%Y/%m/%d")
    
    df
    ## app.R ##
    library(shiny)
    library(shinydashboard)
    
    ui <- dashboardPage(
        dashboardHeader(),
        dashboardSidebar(
            selectInput(inputId = "choosezone", label = "Choose your location",choices = c("LA", "NY")),
            uiOutput("selectdate") 
        ),
        dashboardBody()
    )
    
    server <- function(input, output) {
        output$selectdate = renderUI({
            location_choice = ifelse(input$choosezone == "LA", 1, 2)
                dateRangeInput('dateRange',
                               label = 'Date range input: yyyy-mm-dd',
                               start = df$localtime[location_choice] - 2, end = df$localtime[location_choice] + 2
                )
        })
    
    }
    
    shinyApp(ui, server)