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")))
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With