使用 Shiny 时如何检索客户端的当前时间和时区? [英] How to retrieve the client's current time and time zone when using Shiny?

查看:24
本文介绍了使用 Shiny 时如何检索客户端的当前时间和时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道是否有一些聪明的方法可以让客户端获取当前时间和时区,以便在 Shiny 应用程序的 server.R 部分使用它.如果没有,那么最简单的方法是什么?

I'm wondering if there is some clever way of getting the clients current time and time zone in order to use it in the server.R part of a Shiny application. If not, what could be the easiest way of doing this?

推荐答案

我发现了一种有效的方法,它只是对 在应用加载时将 javascript 变量读入 Shiny/R.它不检索实际时区,而是检索时区偏移量.

I found out a method that works and which is just a small modification of the stackoverflow answer to Reading javascript variable into shiny/R on app load. It does not retrieve the actuall time zone, but well the time zone offset.

在 ui.R

HTML('<input type="text" id="client_time" name="client_time" style="display: none;"> '),
HTML('<input type="text" id="client_time_zone_offset" name="client_time_zone_offset" style="display: none;"> '),

tags$script('
  $(function() {
    var time_now = new Date()
    $("input#client_time").val(time_now.getTime())
    $("input#client_time_zone_offset").val(time_now.getTimezoneOffset())
  });    
')

上面创建了两个 div 并且 javascript 代码检索客户端的时间和时区偏移量并将它们放在 div s 中.

This above created two divs and the javascript code retrieves the clients time and time zone offset and put them in the divs.

在 server.R

client_time <- reactive(as.numeric(input$client_time) / 1000) # in s
time_zone_offset <- reactive(as.numeric(input$client_time_zone_offset) * 60 ) # in s 

上面创建了两个可在服务器代码中使用的反应性变量.为了便于处理,我还将 input$client_time 从 ms 转换为 s,将 input$client_time_zone_offset 从 min 转换为 s.

This above creates two reactive variables that can be used in the server code. For ease of handling I also transform input$client_time from ms to s and input$client_time_zone_offset from min to s.

这篇关于使用 Shiny 时如何检索客户端的当前时间和时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆