Get the user's current date and time in R/Shiny

白昼怎懂夜的黑 提交于 2021-02-07 12:58:23

问题


I am building a shiny app and hosting it on the server. There are date and time inputs. The default value is Sys.Date(). Now when the user accesses it, the default value is taken as server date and time rather than the users.

Please tell me how can I get the user's current time and date and use them as default values into my input box.

Current input scenario:

dateInput("dateto", "Date To:", format = "mm/dd/yyyy", value = Sys.time()),
textInput("dateto_hour", "HH:MM",
                value = gsub("(.*):.*","\\1",format(Sys.time(), "%X")))

回答1:


There are a couple solutions that people have found to this (for example, here), and they all have particular advantages. Since you're looking to use it as the default value in a textInput, this solution that I've adopted for a similar need may work well for you. It involves reading the client's browser time using some JS, assigning that as the default value in a textInput, and then using that textInput later in the server. In my application, I'm using this to timestamp data submissions from the user.

In the UI, you need the follow JS script just before your textInput:

tags$script('
          $(document).ready(function(){
          var d = new Date();
          var target = $("#clientTime");
          target.val(d.toLocaleString());
          target.trigger("change");
          });
          '),
textInput("clientTime", "Client Time", value = "")

As suggested in the comments, session$userData can be used to store session-specific data such as input$clientTime for use and manipulation in the server. Below is a complete app showing the difference between the server time and the client time, but you'll obviously need to publish it to a server in order to see the difference.

library(shiny)

ui <- fluidPage(
  verbatimTextOutput("server"),
  tags$script('
          $(document).ready(function(){
          var d = new Date();
          var target = $("#clientTime");
          target.val(d.toLocaleString());
          target.trigger("change");
          });
          '),
  textInput("clientTime", "Client Time", value = ""),
  verbatimTextOutput("local")
)

server <- function(input, output, session) {

  output$server <- renderText({ c("Server time:", as.character(Sys.time()), as.character(Sys.timezone())) })
  session$userData$time <- reactive({format(lubridate::mdy_hms(as.character(input$clientTime)), "%d/%m/%Y; %H:%M:%S")})
  output$local <- renderText({session$userData$time() })


}

shinyApp(ui = ui, server = server)


来源:https://stackoverflow.com/questions/50395676/get-the-users-current-date-and-time-in-r-shiny

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!