Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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")))
like image 553
Rohit Kumar Singh Avatar asked May 17 '18 15:05

Rohit Kumar Singh


1 Answers

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)
like image 108
phalteman Avatar answered Oct 04 '22 10:10

phalteman