我正在构建一个闪亮的应用程序并将其托管在服务器上。有日期和时间输入。默认值为Sys.Date()。现在,当用户访问它时,默认值将被视为服务器日期和时间而不是用户。
请告诉我如何获取用户当前的时间和日期,并将其作为默认值输入到我的输入框中。
当前输入方案:
dateInput("dateto", "Date To:", format = "mm/dd/yyyy", value = Sys.time()),
textInput("dateto_hour", "HH:MM",
value = gsub("(.*):.*","\\1",format(Sys.time(), "%X")))
答案 0 :(得分:1)
人们已经找到了一些解决方案(例如,here),它们都有特别的优势。由于您希望将其用作textInput中的默认值,因此我针对类似需求采用的此解决方案可能适合您。它涉及使用某些JS读取客户端的浏览器时间,将其指定为textInput中的默认值,然后在服务器中使用该textInput。在我的应用程序中,我使用它来为用户提交数据提交时间戳。
在UI中,您需要在textInput之前使用以下JS脚本:
tags$script('
$(document).ready(function(){
var d = new Date();
var target = $("#clientTime");
target.val(d.toLocaleString());
target.trigger("change");
});
'),
textInput("clientTime", "Client Time", value = "")
根据评论中的建议,session$userData
可用于存储特定于会话的数据,例如input$clientTime
,以便在服务器中使用和操作。下面是一个完整的应用程序,显示服务器时间和客户端时间之间的差异,但您显然需要将其发布到服务器以查看差异。
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)