在 R/Shiny 中获取用户的当前日期和时间

Roh*_*ngh 7 r shiny shinydashboard

我正在构建一个闪亮的应用程序并将其托管在服务器上。有日期和时间输入。默认值为 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")))
Run Code Online (Sandbox Code Playgroud)

pha*_*man 6

人们已经找到了几种解决方案(例如,此处),并且它们都有特定的优点。由于您希望将其用作 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 = "")
Run Code Online (Sandbox Code Playgroud)

正如评论中所建议的,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)
Run Code Online (Sandbox Code Playgroud)